【问题标题】:Laravel: return multiple relationshipsLaravel:返回多个关系
【发布时间】:2017-03-21 13:39:58
【问题描述】:

我有下表:

该表名为user_eggs,它存储用户鸡蛋。 鸡蛋是带有附加数据的项目 (hatch_time)

如您所见,用户 2 有 2 个鸡蛋,分别是项目 46 和 47。

我的items表存储了物品的一般信息,如名称、图片、描述等...

如何使用 $user->eggs() 返回用户鸡蛋,包括鸡蛋 item_iditems 表中的项目数据?

我试过了:

用户模型:

/**
     * Get the eggs
     */
    public function eggs()
    {
        return $this->belongsToMany(Egg::Class, 'user_eggs','user_id','item_id')
        ->withPivot('id','hatch_time');
    }

但是$user->eggs() 返回一个空数组。

有什么想法吗?

【问题讨论】:

  • 在循环记录时您想要hatch_time 还是要对其运行查询?

标签: laravel laravel-5 eloquent


【解决方案1】:

一个简单的方法是: 在您的 UserEgg 模型中定义:

    /**
     * Get the user associated with egg.
     */
    public function _user()
    {
        return $this->belongsTo('App\User','user_id');
    }
    /**
     * Get the item associated with egg.
     */
    public function item()
    {
        return $this->belongsTo('App\Item','item_id');
    }

然后在你的控制器中:

使用模型提取如下所有内容:

$userEggs = UserEgg::where('user_id',2)->get();
foreach($userEggs as $userEgg){
    $associateduser = $userEgg->_user;
    $associatedItem = $userEgg->item;
}

【讨论】:

    【解决方案2】:

    简答

    如果你遍历用户的鸡蛋:

    foreach($user->eggs as $egg){
        $item = Item::find($egg->pivot->item_id);
    }
    

    如果要查询:

    $user->eggs()->wherePivot('item_id', 1)->get();
    

    长答案

    From the Laravel Documentation

    检索中间表列

    正如您已经了解到的,处理多对多关系需要存在一个中间表。 Eloquent 提供了一些非常有用的方式来与这个表进行交互。例如,假设我们的 User 对象有很多与之相关的 Role 对象。访问此关系后,我们可以使用模型上的 pivot 属性访问中间表:

    $user = App\User::find(1);
    
    foreach ($user->roles as $role) {
        echo $role->pivot->created_at;
    }
    

    请注意,我们检索到的每个角色模型都会自动分配一个枢轴属性。该属性包含一个表示中间表的模型,并且可以像任何其他 Eloquent 模型一样使用。

    默认情况下,只有模型键会出现在数据透视对象上。如果您的数据透视表包含额外的属性,您必须在定义关系时指定它们:

    return $this->belongsToMany('App\Role')->withPivot('column1', 'column2');
    

    如果您希望数据透视表自动维护 created_at 和 updated_at 时间戳,请在关系定义上使用 withTimestamps 方法:

    return $this->belongsToMany('App\Role')->withTimestamps();
    

    通过中间表列过滤关系

    您还可以在定义关系时使用 wherePivot 和 wherePivotIn 方法过滤 belongsToMany 返回的结果:

    return $this->belongsToMany('App\Role')->wherePivot('approved', 1);
    
    return $this->belongsToMany('App\Role')->wherePivotIn('priority', [1, 2]);
    

    【讨论】:

    • 正如我所说的user->eggs reutrn一个空数组,所以我不能foreach,有一个问题我不知道是什么
    • 您使用的用户是否正确?如果你转储(dd()$user->eggs() 的结果,你会得到什么?如果你得到一个 Builder 的实例,你应该使用不带括号的$user->eggs
    猜你喜欢
    • 2020-07-31
    • 1970-01-01
    • 2019-01-12
    • 2012-11-26
    • 2019-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-26
    相关资源
    最近更新 更多