我有一个问题,我需要获取拥有博物馆的画廊表和拥有博物馆的用户的所有图像(路径)。我得到了图像的路径,但这些与拥有博物馆的 user_id 无关。
因此,简要说明:
每个用户都拥有一个博物馆,一个博物馆有一个包含多个图像的画廊(图像 url 的路径)
五月表结构
我的画廊模型:
<?php
class Gallery extends \Eloquent {
protected $fillable = [];
public function museums() {
//return $this->belongsToMany('Museums', 'id');
return $this->belongsTo('Gallery', 'museum_id');
}
}
Run Code Online (Sandbox Code Playgroud)
我的博物馆模型
<?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');
}
}
Run Code Online (Sandbox Code Playgroud)
我的用户模型
public function museums()
{
return $this->hasMany('Museum');
}
Run Code Online (Sandbox Code Playgroud)
和我的博物馆控制器
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'));
}
Run Code Online (Sandbox Code Playgroud)
在我看来,我有
@foreach ($gallery as $image)
<img src="{{ $image->path }}" />
@endforeach
Run Code Online (Sandbox Code Playgroud)
你可以试试这个:
// 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');
}
Run Code Online (Sandbox Code Playgroud)
然后在控制器中:
$museums = Museum::with('galleries', 'owner')->get();
return View::make('museums.detail', compact('museums'));
Run Code Online (Sandbox Code Playgroud)
在您看来:
@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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6452 次 |
| 最近记录: |