提问者:小点点

雄辩地解决遥远的关系


假设我有这种结构。

| lines      |   | products |   | orders |
|------------|   |----------|   |--------|
| id         |   | id       |   | id     |
| product_id |   |----------|   |--------|
| order_id   |
|------------|

Laravel雄辩有没有办法加载相关的产品给出订单?我尝试了hasManyPass(产品::class,林e::class),但没有运气,因为在产品表上没有对订单的引用。有没有一种方法可以解决这种关系,或者我应该写一个原始查询?


共1个答案

匿名用户

您可以在订单模型中创建多对多关系:

class Order extends Model
{
    public function products()
    {
        return $this->belongsToMany('App\Product','lines', 'order_id', 'product_id');
    }
}

然后您可以获得与订单相关的产品:

$order_id = 12;
$order = Order::find($order_id);
$order_products = $order->products;