2
我試圖在Laravel應用程序中設置模型關聯。在這個例子中,我有一個Customer模型和一個Store模型。客戶有一個商店,商店屬於許多客戶。Laravel協會,不按預期方式將模型關聯
客戶模式:
public function store() {
return $this->hasOne('store', 'store_id');
}
Store模式:
public function customer() {
return $this->belongsToMany('customer', 'store_id');
}
控制器電話:
public function index() {
$cust = Customer::find('mrowland45');
echo $cust->store->name;
exit;
}
錯誤消息:試圖讓非對象的屬性。所以我顯然沒有正確地進行關聯?在CakePHP中,你會設置你的協會,那麼當你做了一個客戶 - > find()方法,它會給你這樣的事情:
array(
'Customer' => array(
//FIELDS SELECTED HERE
),
'Store' => array(
//FIELDS SELECTED HERE
)
)
,所以如果我做了一個類似的控制器調用這個樣子,這將工作:
public function index() {
$cust = $this->Customer->find('whatever');
echo $cust['Store']['name'];
exit;
}
基本上,我想知道的是我怎麼可以設置模型關聯,這樣的代碼,這樣的線是有效的(或者如果它甚至有可能...):
echo $cust->store->name;
我可能是錯的,但我相信的關係應該是客戶屬於關聯店和專賣店的hasMany的客戶... – 2014-09-05 17:58:39
@TimWithers是的,就是這樣。非常感謝! – mrowland 2014-09-05 18:04:45