Baskets

问题描述 投票:0回答:1

我有3张表。

Users        | Baskets        | Items
--------------------------------------------
id           | id             | id
             | user_id        | basket_id
             |                | price

我想在eloquent中建立一个关系,通过这个关系我可以得到所有物品和相应的篮子,其中物品的价格是X。 我想让我简单地使用$user->物品(x)就能得到结果。

我不确定这是否可以单独使用Relationship来完成,或者我必须要写自定义查询。

任何,以及所有的帮助和指导都将被感激!

laravel eloquent relationship one-to-many laravel-7
1个回答
1
投票

用户模式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);

使用方法

编辑

2
投票

你可以在 hasManyThrough

.

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

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

用户模式

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

© www.soinside.com 2019 - 2024. All rights reserved.