0
我想從我的客戶表的關係加載到我的訂單表,但每一次我嘗試我不斷收到此錯誤:範圍功能Laravel ORM調用關係
Symfony \ Component \ Debug \ Exception \ FatalErrorException Call to a member function where() on a non-object
這裏是我的訂單模式
class Orders extends Eloquent
{
protected $softDelete = true;
public function order_items()
{
return $this->hasMany('Order_item');
}
public function customer()
{
return $this->hasOne('Customer', 'id', 'customer_id');
}
public function client()
{
return $this->hasOne('Client', 'id', 'client_id');
}
public function billingAddress()
{
if($this->client()->first() != null)
{
return $this->client()->getBillingAddress($this->billing_address_id);
}
else
{
return $this->customer()->getBillingAddress($this->billing_address_id);
}
}
}
這裏是我的客戶模型
class Customer extends Eloquent
{
protected $softDelete = true;
public function order()
{
$this->belongsTo('Orders');
}
public function addresses()
{
$this->hasMany('Customeraddress', 'id', 'customer_id');
}
public function scopeGetBillingAddress($query, $addressId)
{
return $this->addresses()
->where('id', '=', $addressId)
->where('type', '=', 'billing');
}
public function scopeGetShippingAddress($query, $addressId)
{
return $this->addresses()
->where('id', '=', $addressId)
->where('type', '=', 'shipping');
}
}
最後這裏是我的customeraddress型號:
class Customeraddress extends Eloquent
{
protected $table = "customer_addresses";
protected $softDelete = true;
public function customer()
{
$this->belongsTo('Customer');
}
}
現在,我想我的控制器上運行該工具來獲取訂單地址,但我不斷收到錯誤。我如何能夠通過雄辯的關係和範圍功能來做到這一點?
$address = Orders::find(21)->billingAddress()->first();
echo $address->street;
感謝您的回覆。我明白了在billingAddress中調用第一個()的意思,我已經刪除了它。但我仍然有一個問題,如果我交換鍵像你一樣狀態我現在得到這個錯誤: > SQLSTATE [42S22]:未找到列:1054'where子句'中的未知列'clients.client_id'(SQL:select *從'客戶端',其中客戶端'.'deleted_at'爲空和'clients'.'client_id' = 21限制1) 用以前的方式,我可以看到,當我調用$ this-> addresses()它會返回我這些值就好像我稱之爲get()或first(),而我沒有。在$ this-> addresses() – yveslebeau
顯示您的客戶和客戶端外鍵後,不會讓我堆棧。你在哪裏調用$ this-> addresses()? –
我的客戶和客戶沒有外鍵,他們是父母。客戶地址和客戶地址向他們各自的父母提供了外鍵。所以客戶會有很多客戶端,因此hasMany('Customeraddress')。因此,明智的是,customer_address表有一個名爲「customer_id」的外鍵,而客戶只有一個主鍵「id」。 – yveslebeau