php - Laravel hasManyThrough 什么都不返回
问题描述
产品:
-----------------------
|id | name | seller_id |
-----------------------
| 1 | bmw | 1 |
-----------------------
| 2 | benz | 1 |
-----------------------
| 2 | reno | 2 |
-----------------------
买:
------------------------------
|id | product_id | buyer_id |
------------------------------
| 1 | 1 | 1 |
------------------------------
| 2 | 1 | 2 |
------------------------------
| 3 | 2 | 22 |
------------------------------
买方:
------------------------------
|id | name | email |
------------------------------
| 1 | john | @ |
------------------------------
| 2 | mike | @ |
------------------------------
| 3 | dave | @ |
------------------------------
解释:
卖家products
入products
桌,买家购买产品后入buy
桌。有buyer
表格也有seller
表格,我想做的是,将这些buyer
数据显示给seller
谁购买了卖家产品。
考虑一下,一个卖家有seller_id
1,制造产品,一些买家购买了他/她的产品,对吗?现在我想向购买了你们产品的卖家展示。john 和 mike 购买了 bmw,现在 id 为 1 的卖家应该在每个产品下看到 mike 和 john 的电子邮件等。
我尝试了什么:
产品控制器.php:
$pro = Product::where('seller_id', $seller->id)->where('deleted', 0)->with('buyer')->get();
产品.php:
function buyer()
{
//return $this->belongsTo('App\Buy', 'id'); // this just show me buyer_id
return $this->hasManyThrough('App\Buyer', 'App\Buy', 'id', 'id', 'product_id', 'buyer_id');
}
这返回我的产品但buyer
为空,我是 laravel 的新手,"buyer": []
我不知道哪个localKey
,,或与哪个表相关。所以知道我做错了什么吗?firstKey
secondKey
secondLocalKey
- 编辑 -
public function userproducts()
{
$seller = Auth::seller();
$pro = Product::where('seller_id', $seller->id)->where('deleted', 0)->with('buyer')->get();
return response()->json($pro, 200 );
}
解决方案
你建立了错误的关系。正如您所解释的,您的产品有很多买家,买家可以购买很多产品。
所以,这将是一个多对多的关系。
尝试建立如下关系,然后检查它是否适合您。
Product.php模型
function buyers(){
return $this->belongsToMany('App\Buyer','Buy_table_name','product_id','buyer_id');
}
在Buyer.php模型中
function products(){
return $this->belongsToMany('App\Product','Buy_table_name','buyer_id','product_id');
}
现在,在控制器文件中使用这个查询。
$pro = Product::where('seller_id', $seller->id)->where('deleted', 0)->with('buyers')->get();
推荐阅读
- android - set.connect 仅适用于第一个按钮
- python - TypeError:需要一个类似字节的对象,而不是“绘图”
- java - 设置为null后如何将onItemClickListener重置为true?
- angular - 在一个角度组件中一次访问所有属性绑定
- reactjs - 使用 React JS 输入地址并显示街景图像
- javascript - array.findIndex 不是函数
- javascript - 奇怪的是,window.document 没有返回理想情况下应该返回的正确对象。为什么?
- touchscreen - 我可以将此触摸屏与我的 ESP32 控制器一起使用吗?
- amp-html - amp-consent 和 IAB 同意字符串实施详细信息
- swift - 使用哪种颜色可以快速反转暗模式