我有一个问题,我需要获取我的画廊桌的所有图像(路径),这些图像拥有博物馆和拥有博物馆的用户。 我得到了图像的路径,但这些与拥有博物馆的user_id无关。
因此,简短说明:
每个用户拥有一个博物馆,博物馆有一个带有多个图像的图库(图像网址的路径)
表格结构
我的画廊模型:
<?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');
}
和我的博物馆控制器
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
答案 0 :(得分:4)
你可以试试这个:
// 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