我有四个表,seller
,products,
和buyers
,downloads
,的逻辑是:卖家可以products
和买家可以购买products
并将其存储在downloads
表中。因此,例如:
卖方:
---------------------
|id | name | phone |
---------------------
| 1 | mike | 989898 |
---------------------
| 2 | joe | 989898 |
---------------------
产品:
---------------------
|id | name | user_id|
---------------------
| 1 | benz | 1 |
---------------------
| 2 | bmw | 1 |
---------------------
买家:
----------------------
|id | name | phone |
----------------------
| 1 | carlos | 989898 |
----------------------
| 2 | nina | 989898 |
----------------------
资料下载:
-----------------------------
|id | product_id | buyer_id |
-----------------------------
| 1 | 1 | 2 |
-----------------------------
| 2 | 2 | 2 |
-----------------------------
因此,考虑到买家用id
2购买了产品,我想获得产品(id 2)和卖方数据(id 1),另一方面,nina
购买了benz
和bmw
,这些产品属于mike,所以我想获得产品数据和卖方数据在BuyerController中。
class Buyer extends Authenticatable
{
...
public function downloads(){
return $this->hasMany('App\Download','buyer_id');
}
public function products(){
return $this->hasManyThrough('App\Product','App\Seller', 'id', 'user_id');
}
}
在控制器中:
public function files()
{
$buyer = Buyer::find($id);
$files = Buyer::with('downloads', 'products')->get();
return $files;
}
它可以正常工作,但没有错误,但是返回错误的数据,例如,买方没有购买的产品,也没有返回卖方的数据,只是返回"laravel_through_key": 1
。第一个功能工作正常,但第二个功能hasManyThrough
无法正常工作。
我是Laravel的新手,特别是关系。我做错了什么?
根据您的解释,Buyer
具有直接关系downloads
和间接关系products
,但后者是通过downloads
,不是sellers
。因此,应为:
class Buyer extends Authenticatable
{
//...
public function downloads()
{
return $this->hasMany(Download::class);
}
public function products()
{
return $this->hasManyThrough(Product::class, Download::class,
'buyer_id', 'id', 'id', 'product_id');
}
}
不要忘记为其他模型编写关系:
class Product extends Model
{
function seller()
{
return $this->belongsTo(Seller::class, 'user_id');
}
function downloads()
{
return $this->hasMany(Download::class);
}
}
class Download extends Model
{
function product()
{
return $this->belongsTo(Product::class);
}
function buyer()
{
return $this->belongsTo(Buyer::class);
}
}
现在您可以使用其功能了:
1.获取买家产品:
>>> App\Buyer::find(2)->products
=> Illuminate\Database\Eloquent\Collection {#3018
all: [
App\Product {#3022
id: 1,
name: "benz",
user_id: 1,
laravel_through_key: 2,
},
App\Product {#3019
id: 2,
name: "bmw",
user_id: 1,
laravel_through_key: 2,
},
],
}
2.与卖家信息相同
>>> App\Buyer::find(2)->products()->with('seller')->get()
=> Illuminate\Database\Eloquent\Collection {#3026
all: [
App\Product {#3034
id: 1,
name: "benz",
user_id: 1,
laravel_through_key: 2,
seller: App\Seller {#3038
id: 1,
name: "mike",
phone: "989898",
},
},
App\Product {#3031
id: 2,
name: "bmw",
user_id: 1,
laravel_through_key: 2,
seller: App\Seller {#3038},
},
],
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句