[英]Laravel belongsTo / hasMany
我遇到了問題,我需要獲取擁有博物館和擁有博物館的用戶的畫廊桌子的所有圖像(路徑)。 我得到了圖像的路徑,但是這些圖像與擁有博物館的user_id沒有關聯。
因此,為了簡短說明:
每個用戶擁有一個博物館,一個博物館擁有一個包含多個圖像的畫廊(圖像URL的路徑)
五月表結構
我的畫廊模型:
<?php
class Gallery extends \Eloquent {
protected $fillable = [];
public function museums() {
//return $this->belongsToMany('Museums', 'id');
return $this->belongsTo('Gallery', 'museum_id');
}
}
我的博物館模型
<?php
class Museum extends Eloquent {
protected $fillable = ['user_id', 'title', 'description'];
public function user()
{
return $this->belongsTo('User');
}
public function gallery()
{
//return $this->belongsToMany('Gallery', 'museum_id');
return $this->belongsToMany('Gallery');
}
}
我的用戶模型
public function museums()
{
return $this->hasMany('Museum');
}
和我的MuseumController
public function show($id)
{
//
//$museum = Museum::where('id', '=', $id)->first();
//return View::make('museums.detail', compact('museum'));
$museum = Museum::findOrFail($id);
$gallery = Gallery::with('museums')->get();
//$museum = Museum::with('gallery')->get();
return View::make('museums.detail', compact('museum', 'gallery'));
}
在我看來,我有
@foreach ($gallery as $image)
<img src="{{ $image->path }}" />
@endforeach
您可以嘗試以下方法:
// In User model
public function museum()
{
return $this->hasOne('Museum');
}
// In Museum model
public function owner()
{
return $this->belongsTo('User');
}
// In Museum model
public function galleries()
{
return $this->hasMany('Gallery');
}
// In Gallery model
public function museum()
{
return $this->belongsTo('Museum');
}
然后在控制器中:
$museums = Museum::with('galleries', 'owner')->get();
return View::make('museums.detail', compact('museums'));
您認為:
@foreach ($museums as $museum)
{{ $museum->title }}
// To get the user id from here
{{ $museum->owner->id }}
// Loop all images in this museum
@foreach($museum->galleries as $image)
<img src="{{ $image->path }}" />
// To get the user id from here
{{ $image->museum->owner->id }}
@endforeach
@endforeach
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.