gpt4 book ai didi

php - 如何用 Eloquent 方式在数据透视表中获取具有特定属性的所有项目?

转载 作者:行者123 更新时间:2023-11-28 23:33:45 25 4
gpt4 key购买 nike

我的循环表有一个“最喜欢的”功能。我试图通过数据透视表来实现这一点。但现在我正试图找到最有效的方式来 Eloquent 地调用所有登录用户最喜欢的循环。

循环表:

    Schema::create('loops', function(Blueprint $table) {
$table->increments('id');
$table->string('name', 35);
$table->string('loop_path', 255);
$table->string('FK_user_id');
});

用户表:

    Schema::create('users', function(Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('password', 60);
});

收藏夹表:

    Schema::create('favourites', function(Blueprint $table) {
$table->increments('id');
$table->integer('FK_user_id')->unsigned();
$table->integer('FK_loop_id')->unsigned();
});

循环.php :

class Loop extends Model {

protected $table = 'loops';
public $timestamps = true;

public function user()
{
return $this->belongsTo('App\User','FK_user_id','id');
}

public function favourites()
{
return $this->belongsToMany('App\User', 'favourites', 'FK_loop_id', 'FK_user_id');
}

}

这就是我现在的实现方式,但似乎效率不高:

    $loops = Loop::with('favourites')->
with('user')->get();

$favouritedLoops = array();

foreach($loops as $loop)
{
//check if logged in user has favourited this
$user_favorites = Favourite::where('FK_user_id', '=', Auth::user()->id)
->where('FK_loop_id', '=', $loop->id)
->first();

if ($user_favorites != null)
{
array_push($favouritedLoops, $loop);
}

}

return Response::json($favouritedLoops);

最佳答案

您应该在User 模型中定义favouritedLoops 方法,然后您可以轻松访问所有收藏的循环。

User.php

public function favouritedLoops()
{
return $this->belongsToMany('App\Loop', 'favourites', 'FK_user_id', 'FK_loop_id');
}

现在返回看起来像:return Response::json(Auth::user()->favouritedLoops);

关于php - 如何用 Eloquent 方式在数据透视表中获取具有特定属性的所有项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36447380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com