2017-05-13 245 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