我第一次尝试使用hasManyThrough关系。但是当我尝试调用该方法时,它什么都不返回。
这是我的数据库:
User:
- id
- (...)
Shipment:
- id
- users_id
- (...)
Shipment_question:
- id
- shipment_id
- (...)
这是我的模型代码。
用户:
public function Shipment()
{
return $this->hasMany('Shipment','users_id');
}
public function Shipment_question(){
return $this->hasManyThrough('Shipment_question','Shipment','users_id','shipment_id');
}
配送费:
public function User()
{
return $this->belongsTo('User','users_id');
}
public function Shipment_question()
{
return $this->hasMany('Shipment_question','shipment_id');
}
Shipment_question:
public function Shipment()
{
return $this->belongsTo('Shipment','shipment_id');
}
这是电话:
Auth::User()->Shipment_question;
我使用barryvdh调试栏查看查询,cargo_question调用应生成查询,但在查询日志中只显示auth :: user查询。
答案 0 :(得分:1)
为了作为动态属性,关系必须是camelCased
,因此重命名:
public function Shipment_question(){
return $this->hasManyThrough('Shipment_question','Shipment','users_id','shipment_id');
}
//to
public function shipmentQuestion(){
return $this->hasManyThrough('Shipment_question','Shipment','users_id','shipment_id');
}
然后你就可以打电话了:
Auth::user()->simpmentQuestion;
否则你可以使用它的唯一方法就是直接调用它作为一种方法:
Auth::User()->Shipment_question()->getResults();
// what gives the same result as dynamic property after fix:
Auth::User()->shipmentQuestion;
一般情况下,Laravel4 +命名约定使用camelCased
方法和属性以及StudlyCased
类强制(如上所述,或至少建议其他情况)。
因此,我建议您将Shipment_question
课程重命名为ShipmentQuestion
。