gpt4 book ai didi

mysql - Laravel 5.1 DBQuery 加入

转载 作者:行者123 更新时间:2023-11-29 01:27:39 25 4
gpt4 key购买 nike

我有两个表:

products: id, name, manufacturer
myproducts:id, user_id, product_id

我通过我的授权 token 知道 user_id。使用此 user_id token ,想从 myproducts 中获取 product_id 和 id,然后查询产品表以获取名称和制造商,其中 mymproducts 中的 product_id 与产品表中的 id 匹配。目标是向用户提供一个可编辑的列表,他/她可以在 myproducts 表中进行编辑。

到目前为止我只能做

$productlist = DB:table('myproducts')->where('user_id', $userid)->get();

这将返回用户拥有的所有产品。但是我在加入表以返回用户拥有的每个产品的产品数据时遇到了问题。

有什么建议吗?

伪代码:

Select * from myproducts wheer user_id = $userid

对于每个产品 -> 获取产品名称和制造商,其中 id 等于 product_id

最佳答案

您可以使用 DB::table 查询来完成此操作,但在 Laravel 中执行此操作的最佳方法是使用 Eloquent 关系。

创建一个 Model对于这两个表,然后使用模型来定义表之间的关系。

完成后,获取用户拥有的产品的产品数据就这么简单:

$productData = User::find(1)->product;

我强烈建议观看这个关于建立 Eloquent 关系的教程,它解释得非常好:

https://laracasts.com/series/laravel-5-fundamentals

关于mysql - Laravel 5.1 DBQuery 加入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33930843/

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