[英]Eloquent ORM object relashionship
我有兩張桌子。 學校和學生。
當我拿到所有學生時
Student::all()->toJson();
我得到了回應
[
{
"id": 1,
"school_id": 1,
"name": "Jhon"
}
]
但實際上我想收到
[
{
"id": 1,
"school": {
"id": 1
},
"name": "Jhon"
}
]
我知道我能做
Student::with(['school']);
但是然后它對學校表進行了額外的查詢,這不是必需的,因為我只需要學校ID,而不是所有其他屬性。
您可以在模型中覆蓋toArray
方法。 toJson
也可能發生同樣的事情,但是toArray
被toJson
調用,並且我認為在toArray
執行此類操作更好
class Student extends Eloquent {
public function toArray($options = 0){
$this->school = ['id' => $this->school_id];
unset($this->school_id);
return parent::toArray($options);
}
}
為了保持模型不變,只更改輸出(可能更好)
public function toArray($options = 0){
$array = parent::toArray($options);
$array['school'] = ['id' => $array['school_id']];
unset($array['school_id']);
return $array;
}
您可以使用Illuminate\\Support\\Collection
的transform
方法獲得更自動化的解決方案:
$students = Student::all();
$students->transform(function($el) {
$el = $el->toArray();
foreach ($el as $k => $v) {
if (substr($k, -3) === '_id') {
$el[substr($k, 0, -3)]['id'] = $v;
unset($el[$k]);
}
}
return $el;
});
return $students;
如果您要多次調用它(我想您會調用),最好的方法是擴展Illuminate\\Database\\Eloquent\\Collection
並添加一個方法來做到這一點。 然后在基本模型上編輯newCollection
方法以使用新的擴展類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.