【问题标题】:Laravel 5, Eloquent relationship/ Method does not existLaravel 5,雄辩的关系/方法不存在
【发布时间】:2018-07-21 18:22:49
【问题描述】:

我在 laravel 5.6 中有 3 个表

第一个表

//Table1> users: id | name
//and in Model: User
public function bookmarks()
{
   return $this->hasMany(Bookmark::class);
}

第二张表

//Table 3> bookmarks: user_id  | bookmarkable_id  | bookmarkable_type     
// and in Model: Bookmark
public function user()
{
    return $this->belongsTo(User::class);
}

public function products()
{
    return $this->morphedByMany('App\Product', 'bookmarkable');
}

第三张桌子

//Table3> products: id | title | user_id
//and in Model: Product
public function user()
{
    return $this->belongsTo(User::class);
}

public function bookmarks()
{
    return $this->morphToMany('App\Bookmark', 'bookmarkable');
}

现在,我想为当前用户返回所有已添加书签的产品:

$products = auth()->user()->bookmarks()->products()->latest()->paginate(18);

但我收到此错误:

“方法 Illuminate\Database\Query\Builder::products 不存在。”

我怎么了?

【问题讨论】:

    标签: php laravel laravel-5 eloquent polymorphism


    【解决方案1】:

    我相信最好的办法是稍微扭转一下你的想法。从 Product 模型开始(因为您想要一个产品集合),然后使用 whereHas 按当前用户 ID 过滤的书签返回。

    $bookmarkedProducts = Product::whereHas('bookmarks', function($q) {
        $q->where('user_id', auth()->id());
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-13
      • 2016-08-27
      • 1970-01-01
      • 2015-12-17
      • 2017-08-22
      相关资源
      最近更新 更多