【问题标题】:Laravel Collection of Multiple relation itemsLaravel 多个关系项的集合
【发布时间】:2017-07-30 01:54:25
【问题描述】:

我有一个用户,他有很多商店,而一个商店有很多产品

现在我想知道,有没有一种方法可以为该用户获取所有产品的集合。

无需遍历他拥有的商店。

当前方法,返回带有产品的商店集合而不是产品集合

$products = \Auth::user()->shops()->with('products')->get();

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    您需要定义一个HasManyThrough relation

    class User extends Model
    {
        ...
        public function products()
        {
            return $this->hasManyThrough('App\Product', 'App\Shop');
        }
        ...
    }
    

    【讨论】:

    • 我收到一个错误:SQLSTATE[42S22]: Column not found: 1054 Unknown column 'skus.shop_id' in 'on clause' (SQL: select skus.*, shops .user_id from skus inner join shops on shops.id = skus.shop_id where shops.user_id = 2),哦,(SKU = PRODUCT)跨度>
    【解决方案2】:

    您可以使用pluck方法从多个商店获取所有产品。

    public function products()
    {
        return $this->shops->pluck('products');
    }
    
    public function shops()
    {
        return $this->belongsToMany(Shop::class);
    }
    

    ($this 是您的用户模型的一个实例)

    并且在您的商店模型上,您必须与产品有 Laravel 关系

    public function products()
    {
        return $this->belongsToMany(Product::class);
    }
    

    【讨论】:

    • 如果我将它命名为“getProductsAttribute”,它就可以工作,否则它告诉一个关系方法必须返回一个关系。
    • 您的用户模型必须与商店相关,您的商店模型必须与产品相关。
    猜你喜欢
    • 1970-01-01
    • 2017-10-10
    • 1970-01-01
    • 2019-01-04
    • 1970-01-01
    • 2019-06-17
    • 1970-01-01
    • 1970-01-01
    • 2017-01-22
    相关资源
    最近更新 更多