【问题标题】:How to get items from many to many relationships' one to many relationship in Laravel?如何在 Laravel 中从多对多关系的一对多关系中获取项目?
【发布时间】:2016-07-20 17:04:51
【问题描述】:

我有两个关系:

  1. Agents(many)-to-Properties(many) 关系(使用数据透视表)。
  2. Properties(one)-to-Images(many) 关系(无数据透视表)。

所以一个Agent可以有10个Properties,每个Property会有10个Image;因此,Agent 有 100 张图像。 (我不想在代理和图像之间建立关系)。

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

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

【问题讨论】:

    标签: sql database laravel orm relationship


    【解决方案1】:

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

    在您的代理模型中:

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

    然后就可以使用了

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

    【讨论】:

    • 只有当中间关系为hasOnehasMany时,才能使用hasManyThrough。在这种情况下,中间关系是belongsToMany,所以hasManyThrough将不起作用。
    【解决方案2】:

    那么,两个查询怎么样:

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

    【讨论】:

      【解决方案3】:

      hasManyThrough('App\Image', 'App\Property') 如果您与 1-Many 关系存在 1-Many(或 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.*');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-10-03
        • 1970-01-01
        • 2019-07-17
        • 1970-01-01
        • 2018-06-15
        • 1970-01-01
        • 1970-01-01
        • 2019-05-23
        相关资源
        最近更新 更多