When calling CollegeMajor::with('majors')->get()
, I would like to apply the following raw sql query:
TRIM(TRAILING SUBSTRING_INDEX(parent_id, ':', -1) FROM parent_id)
to the parent_id
column. The values in parent_id are stored as 1:1234, 1:3121, 1:1332
etc... and so therefore I'd like to strip everything after the colon. The primary key for CollegeMajor is id and those values are integers like 1
. I get the error below because Laravel believes the raw query is the name of the column. How do I tell Laravel to apply that sql query to project_id
column when executing the relationship?
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');
}
}
Error
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 table
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
How to make it return?
[
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'
}
]
....
]