如何在Laravel中获取多对多关系的一对多关系的项目?

How to get items from many to many relationships' one to many relationship in Laravel?

我有 2 个关系:

  1. Agents(many)-to-Properties(many) 关系(带有枢轴 table)。
  2. 属性(一)到图像(多)关系(无主元table)。

所以一个 Agent 可以有 10 个 Properties,每个 属性 将有 10 个 Images;因此,Agent 有 100 张图像。 (我不想在代理和图像之间创建关系)。

是否有一个查询可以让我获得所有代理的图像?

类似于$agent->properties()->images()->get()

你可以使用 hasManyThrough https://laravel.com/docs/5.1/eloquent-relationships#has-many-through

在您的 Agent 模型中:

public function images()
{
    return $this->hasManyThrough('App\Images', 'App\Properties');
}

那你就可以使用

$agent->images()->get();

那么,两个查询怎么样:

<?php

$agent = new Agent();
$image = new Image();
$propertyIds = $agent->properties()->lists('id');
$images = $image->newQuery()->whereIn('property_id', $propertyIds)->get();

hasManyThrough('App\Image', 'App\Property') 如果您有一对多(或 1-1)关系到一对多关系,则有效。但在我的特定场景中,我有一个多对多关系(带枢轴)到一对多关系。

我最终使用了这个语句。也许这对某人有用:

SELECT images.* FROM `agent_property` INNER JOIN images 
    ON agent_property.property_id = images.property_id 
WHERE agent_property.agent_id = '1'

相当于:

return DB::table('agent_property')->join('images', 'agent_property.property_id', '=', 'images.property_id')->where('agent_property.agent_id', $this->id)->select('images.*');