我有3张桌子。
Car - Door - Fan
汽车可以有一个或多个门。 一扇门可以有一个或多个风扇。
结构
Car - id |名称
门 - id | car_id |侧
粉丝 - id | door_id |颜色
我的模型已定义:
汽车
public class Car extends Eloquent{
protected $table = "car";
public function door()
{
$this->hasMany('Room');
}
}
门
public class Door extends Eloquent{
protected $table = "door";
public function car()
{
$this->belongsTo('Car');
}
public function fan()
{
$this->hasMany('Fan');
}
}
范
public class Fan extends Eloquent{
protected $table = "fan";
public function door(){
$this->belongsTo('Door');
}
}
我可以找回与汽车相关的门,但不能检索与门相关的风扇
这很好用,但是当我尝试检索门的扇子时,它会抛出一个错误
$car = Car::find(1);
foreach($car->door as $dr)
{
echo $dr->side;
}
-
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
$car = Car::find(1);
foreach($car->door as $dr)
{
echo $dr->size;
foreach($dr->fan as $fn)
{
echo $color;
}
}
答案 0 :(得分:2)
您需要为所有关系添加return
,例如
public class Car extends Eloquent{
protected $table = "car";
public function doors() // doors with 's' because many
{
return $this->hasMany('Door'); // Door for class not door
}
}
并使用eager loading来缓解N + 1查询
答案 1 :(得分:0)
Fan模型中的这一行
$this->belongsTo('door');
需要父模型的精确拼写,因此它应该是
$this->belongsTo('Door');
首都为'D'。