laravel hasManyThrough的逆

3npbholx  于 2023-04-22  发布在  其他
关注(0)|答案(1)|浏览(121)

如果我有三张table:

工厂和订单之间没有直接的关系,所以在can I want to get all orders from a factory中,我使用了hasManyThrough关系。

//Factory Model
public function orders()
{
    return $this->hasManyThrough(
        Order::class,
        Product::class,
    );
}

现在,我怎么能颠倒关系?如何从订单中得到工厂而不经过产品

$order->factory ✅ <-- I want this
$order->product->factory ❌
jgovgodb

jgovgodb1#

您可以在Order模型中使用hasOneThrough

use Illuminate\Database\Eloquent\Relations\HasOneThrough;

public function factory(): HasOneThrough
{
   return $this->hasOneThrough(
      Factory::class,
      Product::class,
      'id',
      'id', 
      'product_id',
      'factory_id',  
   );
}

相关问题