Reputation: 1903
Products:
-----------------------
|id | name | seller_id |
-----------------------
| 1 | bmw | 1 |
-----------------------
| 2 | benz | 1 |
-----------------------
| 2 | reno | 2 |
-----------------------
Buy:
------------------------------
|id | product_id | buyer_id |
------------------------------
| 1 | 1 | 1 |
------------------------------
| 2 | 1 | 2 |
------------------------------
| 3 | 2 | 22 |
------------------------------
Buyer:
------------------------------
|id | name | email |
------------------------------
| 1 | john | @ |
------------------------------
| 2 | mike | @ |
------------------------------
| 3 | dave | @ |
------------------------------
Explaination:
Seller products
store in products
table, after buyer bought products, it store in buy
table. there are buyer
table and also seller
table, what I want to do is, show those buyer
data to seller
who has bought seller products.
Consider, a seller with seller_id
1, made products, some buyers bought his/her products, right? now I want to show to seller, who bought your products. john and mike bought bmw, now seller with id 1 should see mike and john email and etc under each products.
What I tried:
ProductController.php:
$pro = Product::where('seller_id', $seller->id)->where('deleted', 0)->with('buyer')->get();
Product.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');
}
This return me products but buyer
is empty "buyer": []
, I'm new to laravel, I don't know which localKey
, firstKey
, secondKey
or secondLocalKey
related to which table. So any idea what I have done wrong?
-- Edit --
public function userproducts()
{
$seller = Auth::seller();
$pro = Product::where('seller_id', $seller->id)->where('deleted', 0)->with('buyer')->get();
return response()->json($pro, 200 );
}
Upvotes: 0
Views: 74
Reputation: 15316
You're making the wrong relationship. As you explain your Product has many buyers and the buyer can purchase many Products.
So, It'll be a Many-to-Many Relationship.
Try to make relationship as below and then check it'll work for you.
Product.php Model
function buyers(){
return $this->belongsToMany('App\Buyer','Buy_table_name','product_id','buyer_id');
}
In Buyer.php Model
function products(){
return $this->belongsToMany('App\Product','Buy_table_name','buyer_id','product_id');
}
Now, use this query in controller file.
$pro = Product::where('seller_id', $seller->id)->where('deleted', 0)->with('buyers')->get();
Upvotes: 1