如何使用eloquent获取枢轴表中具有特定属性的所有项目?

时间:2016-04-06 09:45:38

标签: php mysql laravel eloquent

我有一个最喜欢的'我的循环表的功能。我试图通过数据透视表来实现这一目标。但是现在我试图找到一种最有效的方式来用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();
    });

Loop.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);

1 个答案:

答案 0 :(得分:1)

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

<强> user.php的

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

现在返回将如下所示: return Response::json(Auth::user()->favouritedLoops);