Laravel关联,而不是像预期的那样关联模型


Laravel associations, not associating the Models as expected

我正在尝试在Laravel应用程序中设置模型关联。在这个例子中,我有一个Customer模型和一个Store模型。客户有一个商店,商店属于许多客户。

客户型号:

public function store() {
    return $this->hasOne('store', 'store_id');
}

店铺型号:

public function customer() {
    return $this->belongsToMany('customer', 'store_id');
}

控制器呼叫:

public function index() {
    $cust = Customer::find('mrowland45');
    echo $cust->store->name;
    exit;
}

错误消息:正在尝试获取非对象的属性。所以我显然没有正确地进行联想?在CakePHP中,你会建立你的关联,然后当你执行Customer->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;

它应该是laravel的一对多关系。这意味着你的顾客属于一家商店,但商店有很多顾客。

型号看起来像

客户型号

public function store()
{
    return $this->belongsTo('Store');
}

商店型号

public function customer()
{
    return $this->hasMany('Customer');
}

现在你可以了。

$cust = Customer::find(1);
$cust->store->name;