由于某种原因,我无法链接模型对象。我正在尝试为“订单”加载“位置”,并希望逻辑包含在模型本身中。但是过去的一个链条,它不起作用。
class Order extends Eloquent {
protected $table = 'orders';
public function customer() {
return $this->belongsTo('Customer');
public function location() {
return $this->customer()->location(); // this does not work
}
}
class Customer extends Eloquent {
protected $table = 'customers';
public function user() {
return $this->belongsTo('User');
}
public function orders() {
return $this->hasMany('Order');
}
public function location() {
return $this->user()->location();
// return $this->user(); // WORKS!!
}
}
class User extends Eloquent {
protected $table = 'users';
public function locations() {
return $this->hasMany('Location');
}
public function location() {
return $this->locations()->first();
}
}
我最终想要这样做:
class ChefController extends BaseController {
public function get_orders() {
$chef = $this->get_user_chef(); // this already works
return $chef->orders()->with('location')->get(); // does not work
}
}
答案 0 :(得分:0)
尝试通过添加user_id作为第二个参数来引用关系(用户表),如下所示:
public function user() {
return $this->belongsTo('User',"user_id");
}
也许您将 id 字段称为不同,但您知道我的意思。