Laravel nested eager loading and laravel nested desire
Today, I encountered A small problem when I used demand table A to query site type table B and then used the site type id in Table B to query the site type name in Table C.
Fields in requirement Table A: id, user_id, name, and so on;
Fields in the intermediate Table B: id, appeal_id, and field_type_id;
Fields in site type Table C: id and display_name;
In the Appeal model:
public function appeal_field_type() {
return $this->hasMany('App\Models\AppealFieldType');
}
Public function field_type (){
Return $ this-> belonsto ('app \ Models \ fieldtype')-> select ('id', 'display _ name ');
}
Appeal controller;
$ Result = Appeal: select ('id', 'name ')
-> Where ('id', $ id)
-> With ('appeal _ field_type.field_type ')
-> First ();
All of the above are based on laravel's nested eager loading. Then, according to the method he mentioned above, He imitated and wrote it. As a result, this method always reports an error and the "field_type" method does not exist, I couldn't figure it out at first. I read the appeal model on the right, checked whether the words were wrong, and introduced the model. I thought it was wrong, I load it strictly according to the nested thirst type written in the school, but it is wrong. Later, I thought that since the appeal_field_type method is accessed through the Associated Model, does it still need to access the field_type method through the AppealFieldType model, I wrote the fiel_type METHOD TO THE AppealFielType model, and then accessed it ~
Final success result:
In the Appeal model:
Public function appeal_field_type (){
Return $ this-> hasMany ('app \ Models \ appealfieldtype ');
}
In the AppealFieldType model:
public function field_type() {
return $this->belongsTo('App\Models\FieldType')->select('id','display_name');
}
In Appeal controller:
$ Result = Appeal: select ('id', 'name ')
-> Where ('id', $ id)
-> With ('appeal _ field_type.field_type ')
-> First ();
The main reason is that this part of the school is not particularly clear, and I don't know which controller the later method should be written in. So there is such a new problem ~