产品:
-----------------------
|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
是空的"buyer": []
,我是新来laravel,我不知道是哪个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();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句