【问题标题】:How can I write the join query using eloquent ORM of Laravel如何使用 Laravel 雄辩的 ORM 编写连接查询
【发布时间】:2014-12-24 17:15:15
【问题描述】:

目前我有三个表,其中一个是具有以下列的属性表:

  • 身份证
  • 姓名
  • 说明

第二个是包含以下列的标签表:

  • 身份证
  • 标签名称
  • 标签状态

第三个是具有以下列的数据透视表:

  • 身份证
  • tag_id
  • property_id

现在在属性模型中,我已经定义了与数据透视表的关系,如下所示:

 public function tags()
    {
        return $this->belongsToMany('Tag');
    }

在标签模型中,我定义了与数据透视表的关系,如下所示:

public function properties()
    {
        return $this->belongsToMany('Property');
    }

现在我需要的是如何使用 Laravel 的 eloquent ORM 在这三个表上编写以下查询:

 $propertyTags=Property::join('property_tag', 'properties.id', '=', 'property_tag.property_id')
             ->join('tags', 'tags.id', '=', 'property_tag.tag_id')
             ->where('properties.id','=',$property_id)
             ->get(['tags.tag_name','tags.id']);

【问题讨论】:

    标签: laravel orm eloquent


    【解决方案1】:

    你可以试试

    $property_obj = Property::find($property_id);
    $property_tags = $property_obj->tags->all();
    

    或使用急切加载

    $property_with_tags = Property::with('tags')->where('id','=',$property_id)->get();
    

    【讨论】:

      猜你喜欢
      • 2016-02-26
      • 2015-03-15
      • 1970-01-01
      • 1970-01-01
      • 2013-08-19
      • 1970-01-01
      • 2018-01-26
      • 2021-07-23
      相关资源
      最近更新 更多