Laravel 5.8 中的 hasManyThrough 关系
hasManyThrough relationship in Laravel 5.8
我有以下结构:
Order
id
Order_Products
id
order_id
product_id
Products
id
我正在尝试使用 hasManyTrough (https://laravel.com/docs/5.8/eloquent-relationships#has-many-through)。
我有类似的东西
class Order extends Model{
...
public function products()
{
return $this->hasManyThrough('App\Product', 'App\OrderProduct', 'product_id', 'id', 'order_id', 'id');
}
...
}
我无法让它工作。我很困惑,谁能帮帮我。
感谢 Tim Lewis,我需要 belongsToMany,因为 order_products 是枢轴 table。像这样。
public function products()
{
return $this->belongsToMany('App\Product', 'order_products', 'order_id', 'product_id');
}
在这种情况下,您需要使用 belongsToMany
关系。
关于Has Many Through
的一点点。
表格:
Product
id
Order
id
product_id
Order_Category
id
order_id
在这种情况下,您可以获得 Order Categories
for Product
class Product {
// ...
order_categories() {
return $this->hasManyThrough('App\Post', 'App\User');
}
// ...
}
Laravel 做这样的事情。
$orderIds = Order::query()
->where('product_id', $product->id)
->get(['id'])
->pluck('id');
$orderCategories = OrderCategory::query()
->whereIn('order_id', $orderIds)
->get();
我有以下结构:
Order
id
Order_Products
id
order_id
product_id
Products
id
我正在尝试使用 hasManyTrough (https://laravel.com/docs/5.8/eloquent-relationships#has-many-through)。
我有类似的东西
class Order extends Model{
...
public function products()
{
return $this->hasManyThrough('App\Product', 'App\OrderProduct', 'product_id', 'id', 'order_id', 'id');
}
...
}
我无法让它工作。我很困惑,谁能帮帮我。
感谢 Tim Lewis,我需要 belongsToMany,因为 order_products 是枢轴 table。像这样。
public function products()
{
return $this->belongsToMany('App\Product', 'order_products', 'order_id', 'product_id');
}
在这种情况下,您需要使用 belongsToMany
关系。
关于Has Many Through
的一点点。
表格:
Product
id
Order
id
product_id
Order_Category
id
order_id
在这种情况下,您可以获得 Order Categories
for Product
class Product {
// ...
order_categories() {
return $this->hasManyThrough('App\Post', 'App\User');
}
// ...
}
Laravel 做这样的事情。
$orderIds = Order::query()
->where('product_id', $product->id)
->get(['id'])
->pluck('id');
$orderCategories = OrderCategory::query()
->whereIn('order_id', $orderIds)
->get();