2017-05-13 132 views
-1

我試着像頁面上顯示所有位置:如何在Laravel中創建關係?

{{$item->country()->first()->name}}, {{$item->city()->first()->name}}, {{$item->location()->first()->name}} 

你可以從關係countrycitylocation看到這些值。

如何在這種情況下創建存取器?在哪個模型中寫入訪問器?

我嘗試這樣做:

public function setTeacherNameAttribute() 
    { 

     $this->attributes['teacher_name'] = $this->country->name; 


    } 
+0

我不明白你要做什麼。 「在這種情況下如何創建存取器?在哪個​​模型中寫入存取器?」這個訪問器會做什麼? – devk

回答

0

讓說你的$項目的模型稱爲項目所以這樣做它:

protected $appends = ['address']; 

public function getAddressAttribute(){ 
    $address = ''; 

    if (!empty($item->country())) $address .= $item->country()->first()->name; 
    if (!empty($item->city())) $address .= $item->city()->first()->name; 
if (!empty($item->location())) $address .= $item->location()->first()->name; 
return $address; 
} 

那麼你可以使用它像這樣$item->address

注:變化地址其他任何事情,如果你已經有一個同名的列。

0

無論使用關係或只是簡單的模型,存取總是訪問通過最後模型。在你的情況下,在country,citylocation模型。

下面的方法創建name屬性的訪問:

public function getNameAttribute($value) { 
    // do something with value, or not 
    return $value; 
} 
+0

我不明白你的答案的意思。是否有可能創建存取? – John

+0

是的,只需將此方法添加到上述模型之一即可。這基本上是一個訪問者。 –

+0

我不需要在每個模型中使用分離的訪問器。我需要結合所有來自其他模型的訪問器/ – John