gpt4 book ai didi

php - 将额外模型附加到 BelongstoMany 关系

转载 作者:行者123 更新时间:2023-12-02 19:21:21 24 4
gpt4 key购买 nike

我有两个带有数据透视表的表(用户和饮料),用户与配置文件表有 hasOne 关系,有没有办法将配置文件表附加到数据透视表并获取所有数据。

表格用户

id | name | email

表格配置文件

id | user_id | picture

餐 table 饮料

id | name | price

数据透视表user_drinks

id | user_id | drink_id | quantity | price | status

饮料模型

public function users()
{
return $this->belongsToMany('App\User', 'user_drinks', 'drink_id', 'user_id')->withPivot('price', 'quantity')->withTimestamps();
}

用户模型

public function drinks()
{
return $this->belongsToMany('App\Drink', 'user_drinks', 'drink_id', 'user_id')->withPivot('price', 'quantity')->withTimestamps();
}

public function profile() {
return $this->hasOne('App\Profile');
}

PS:我不想用原始 SQL 查询来写这个,它让我发疯。

最佳答案

我不会更改表关系。我会使用->with()函数获取现有关系中的个人资料信息。

所以$user->drinks()->where('drink_id', $drink_id)->with('profile')->get();这是我的猜测。

关于php - 将额外模型附加到 BelongstoMany 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63021679/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com