Laravel 5.2在定义自引用模型关系时使用原始查询?

时间:2017-01-30 02:52:44

标签: php mysql laravel laravel-eloquent

调用CollegeMajor::with('majors')->get()时,我想应用以下原始sql查询:  TRIM(TRAILING SUBSTRING_INDEX(parent_id, ':', -1) FROM parent_id)parent_id。 parent_id中的值存储为1:1234, 1:3121, 1:1332等...因此我想在冒号后删除所有内容。 CollegeMajor的主键是id,这些值是1之类的整数。我收到下面的错误,因为Laravel认为原始查询是列的名称。在执行关系时,如何告诉Laravel将该sql查询应用于project_id列?

CollegeMajor.php

class CollegeMajor extends Model {
   public function majors() {
     return $this->hasMany('App\Models\CollegeMajor', \DB::raw(TRIM(TRAILING SUBSTRING_INDEX(parent_id, ':', -1) FROM parent_id)))
                  ->where('entity', 'major');
   }
}

错误

Unknown column 'college_major.TRIM(TRAILING SUBSTRING_INDEX(parent_id, ':', -1) FROM parent_id)' in 'where clause' (SQL: select * from `college_major` where `entity` = major and `college_major`.`TRIM(TRAILING SUBSTRING_INDEX(parent_id, ':', -1) FROM parent_id)` in (1, 2, 3, 4, 5, 6, 7, 8))

college_majors表

id      name             entity   parent_id
1   College of Art       college     1234
2   College of Business  college     4567
3   Art History          major     1:1234
4   Asian Art            major     1:1234
5   Accounting           major     2:4567
6   Marketing            major     2:4567

如何让它回归?

[
  id: 1,
  name: 'College of Art',
  entity: 'college',
  parent_id: 1234,
  majors: [
    {
      id: 3,
      name: 'Art History',
      entity: 'major',
      parent_id: '1:1234'
    },
    {
      id: 4,
      name: 'Asian Art',
      entity: 'major',
      parent_id: '1:1234'
    }

  ]
  ....
]

1 个答案:

答案 0 :(得分:0)

<<-的第二个参数是外键。所以你不能在那里定义你的查询。按如下方式定义您的关系。

hasMany()

然后当你查询时使用raw expressions这个。

public function majors() { 
     return $this->hasMany('App\Models\CollegeMajor'); 
}

尚未测试过。在我的手机上:))