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

时间:2021-06-30 12:34:36

I have a 'favourite' functionality for my loops table. I am trying to achieve this with a pivot table. But now I'm trying to find the most efficient way to call all the logged in users favourited loops with eloquent.

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

loops table :

循环表:

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

users table:

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

favourites table :

收藏表:

    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');
    }

}

This is how I achieve this now , but it doesn't seem efficient :

这就是我现在实现这一目标的方法,但它看起来效率不高:

    $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 个解决方案

#1


1  

You should define favouritedLoops method in User model, then You can easily access all favourited loops.

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

User.php

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

and return now will look like: return Response::json(Auth::user()->favouritedLoops);

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

#1


1  

You should define favouritedLoops method in User model, then You can easily access all favourited loops.

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

User.php

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

and return now will look like: return Response::json(Auth::user()->favouritedLoops);

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