2017-08-24 118 views
1

訪問多個遠程模型我有三個型號在Laravel 5.4 - 更新

Photo 
-id 
-path_full 
Person 
-id 
-name 
Face 
-id 
-person_id //was people_id 
-photo_id 

我想從照片模式訪問的人的名字。
面模型:

public function photo() 
{ 
    return $this->belongsTo(Photo::class); 
} 

public function person() 
{ 
    return $this->belongsTo(Person::class); 
} 

照片型號:

public function faces() 
{ 
    return $this->hasMany(Face::class); 
} 

角色模型:

public function faces() 
{ 
    return $this->hasMany(Face::class); 
} 

在我控制我加載照片是這樣的:

$photos = Photo::with('faces')->paginate(); 

在我的刀片模板中,我想訪問照片中的人臉名稱。 我明白了這一點。
這是在foreach因此奇異$照片:

{{implode($photo->faces->pluck('people_id')->toArray(),', ')}} 

我怎樣才能得到,而不是人的名字?

解決方案
我需要這在我看來並注意我改變了分貝PERSON_ID如此雄辯可以做它的魔力。

//Controller: 
$photos = Photo::with('faces.person')->paginate(); 

//View: 
@foreach($photo->faces as $face) 
     {{$face->person['name']}} 
@endforeach 
+0

這不是一個多對多的關係嗎? –

+0

臉部是特定照片中的獨特臉部,因此它總是屬於單張照片。這從面部識別。一個人在許多照片中可以有許多面孔。一張臉只能屬於一個人。 – BobB

+0

所以,你想要拍一張照片,然後是每張臉的人名? –

回答

2

可以急於負載person數據你對照片的模型調用faces時間

// Photo.php 
public function faces() 
{ 
    return $this->hasMany(Face::class)->with('person'); 
} 

或者在您的查詢,你只能在那做是爲了急於負載時間

$photos = Photo::with('faces', 'faces.person')->paginate(); 

現在您可以像這樣訪問:

$photos->first()->faces->first()->person->name; // will print the name of the person of the first face of the first photo... 

我希望這個答案能夠有所幫助。

+0

當I DD($光電>面)我得到這樣的:收集{#355▼ #items:陣列:1 [▼ 0 =>臉部{#376▼ #table: 「面」 #attributes:數組:13 [▼ 「ID」=> 181 「photo_id」=> 16 「people_id」=> 1 ] #relations:陣列:1 [▼ 「人」=>空 ] } ] }注意人員爲空。 – BobB

+0

感謝您的幫助。我的問題是people_id應該是person_id。 Laravel的模型名稱不是表名 – BobB

+0

很棒的@BobB,我認爲如果你更新你的問題會很有幫助。 –

0

嘗試通過改變您的查詢像這樣得到的臉的人:

Photo::with(['faces' => function($query) {$query->with('person')}])->paginate(); 

我不太清楚有關語法,但是這是一個雄辯的模型,你可以嵌套關係如何。一個更短的方式來寫這可能是:Photo::with('faces.person')->paginate();

提供了一些更多的信息here