【问题标题】:Laravel getting data from a deep relationshipLaravel 从深度关系中获取数据
【发布时间】:2020-08-17 11:30:55
【问题描述】:

我有 3 张桌子:

Users Baskets Items
id id id
user_id basket_id
price

我正在尝试建立一个 eloquent 的关系,通过它我可以获得所有的项目和相应的篮子,其中项目的价格是 X。我想要它,以便我可以简单地使用 $user->items(x ) 并得到结果。

我不确定这是否可以单独使用关系来完成,或者我是否必须求助于编写自定义查询。

我们将不胜感激任何和所有的帮助和指导!

【问题讨论】:

  • 我用 laravel 很久了,记不清函数名了等于用户中的 user_id ,之后您可以在项目和篮子之间建立关系,因为现在在第一步之后您将只有一个级别的关系,希望对您有所帮助。祝你好运..

标签: laravel eloquent relationship one-to-many laravel-7


【解决方案1】:

您要查找的关系是hasManyThrough

https://laravel.com/docs/7.x/eloquent-relationships#has-many-through

用户模式

public function items()
{
    return $this->hasManyThrough(Item::class, Bucket::class);
}

你想用的方式我想是不可能实现的。

可能的用途

$user->items()->where('price', x);

如果你定义了自定义范围

物品模式

public function scopeWherePrice($query, $value)
{
    return $query->where('price', $value);
}

用法

$user->items()->wherePrice(x);

编辑

如果你真的想写像$user->items(x) 这样的代码,你可以在User Modal 上定义一个方法。

请注意,这不是关系,只是另一种获取结果的方法。

用户模式

public function items($price)
{
    return this->items()->where('price', $price)->get();
}

【讨论】:

    【解决方案2】:

    使用hasManyThrough 定义模型中的关系:

    用户模型

     /**
     * Get all of the items & baskets for the user.
     */
     public function items($price)
     {
        return $this->hasManyThrough('App\Items', 'App\Baskets')
            ->with('basket')
            ->where('price',$price);
     }
    

    篮子模型

     /**
     * Get the Items's Basket.
     */
     public function basket()
     {
        return $this->belongsTo('App\Basket','basket_id');
     }
    

    然后这样称呼它:

     $user->items(x);
    

    这将以特定价格返回所有用户物品及其对应的购物篮。

    【讨论】:

      猜你喜欢
      • 2020-07-01
      • 2018-02-14
      • 2021-08-06
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      • 2021-05-05
      • 1970-01-01
      • 2021-12-10
      相关资源
      最近更新 更多