【发布时间】:2021-02-01 07:50:21
【问题描述】:
我的数据库中有以下结构。
users
--
id
...
products
--
id
...
licenses (pivot table with some extra informations these data are grabbed via API)
--
user_id
product_id
license_key
license_type
url
purchased_at (datetime)
supported_until (datetime)
...
这是我模型中的代码:
# User has many licenses
# User has many products through licenses
User
// User has many licenses.
public function licenses()
{
return $this->hasMany(License::class);
}
// User has many products
// Expected: products
// Outcome: not getting
public function products()
{
return $this->belongsToMany(Product::class, 'licenses', 'user_id', 'product_id')
->using(License::class);
}
产品型号。
# Product has many licenses
Product
public function licenses()
{
return $this-hasMany(License::class);
}
许可模式
# License belongs to an user.
# License belongs to a product.
License
public function user()
{
return $this->belongsTo(User::class);
}
public function product()
{
return $this->belongsTo(Product::class);
}
路线
// 导入这些类命名空间并应用所有必要的中间件。
Route::get('/my-products', [ProductController::class, 'index']);
在产品控制器中
ProductController
public function index()
{
$user = Auth::user();
// This doesn't get any products. Which is what I want to use.
$products = $user->products;
// This works but I want to display more efficiently and using less DB query.
$licenses = $user->licenses;
$products = [];
foreach ($licenses as $license) {
array_push( $products, $license->product)
}
// Get unique products of an user through licenses relation.
$products = collect($products)->unique();
}
使用$user->products 时,我没有从许可关系中获得任何产品
如果页面中有超过 5 个产品,我想对产品进行分页,并减少额外的数据库查询和模型加载层。请建议一些更好的方法。
【问题讨论】:
标签: php eloquent pivot-table relationship laravel-8