我的循环表有一个"最喜欢的"功能。我正试图通过一个数据透视表来实现这一点。但现在我正试图找到最有效的方法,用雄辩的方式调用所有登录用户喜欢的循环。
循环表:
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();
});
Loop.hp:
class Loop extends Model {
protected $table = 'loops';
public $timestamps = true;
public function user()
{
return $this->belongsTo('AppUser','FK_user_id','id');
}
public function favourites()
{
return $this->belongsToMany('AppUser', '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('AppLoop', 'favourites', 'FK_user_id', 'FK_loop_id');
}
现在返回的情况如下:return Response::json(Auth::user()->favouritedLoops);