假设以下型号:
class Character extends Model
{
protected $fillable = ['items'];
protected $guarded = ['id'];
public function items(){
return $this->hasMany("App\Item");
}
}
class Item extends Model
{
public function character(){
return $this->belongsTo("App\Character");
}
}
发出请求时,控制器执行以下操作:
public function getCharacter(Request $request, $characterID = 0){
$characters = array(Character::find($characterID));
foreach($characters as $key => $value){
//ADD THE ITEMS
$characters[$key]->items = $characters[$key]->items;
}
return $characters;
}
------ 这很好用。
我得到一个字符json,其成员“items”包含相应项目模型的所有数据。
但,假设Items
不属于Character
,而属于ItemPackage
。具体来说,Items
属于ItemPackage
(ItemPackage
有许多Items
)而ItemPackage
属于Character
(Character
有很多ItemPackage
{1}}(s))
以类似的方式,我尝试在控制器中执行以下操作,但它不起作用。
....
foreach($characters as $key => $value){
//ADD THE ITEM
$characters[$key]->itemPackages = $characters[$key]->itemPackages
//the above line works but we also need to add the item obj data so:
foreach($characters[$key]->itemPackages as $key2){
$characters[$key]->itemPackages[$key]->arrayOfItems = "whatever here";
}
}
....
具体来说,我得到一个错误:未定义的偏移:1。我显然不理解我操作得非常好的数据结构,也许有人可以照亮我。
感谢您抽出时间
答案 0 :(得分:0)
解决方法是:
$characters = Character::with('itemPackages')->with("itemPackages.items")->get();