我试图通过Eloquent获取Laravel中属于特定专辑的所有图像。这些是我的表格:
Table: albums
Rows: id, name, description, user_id
Table: album_images
Rows: id, file_name
Table: album_album_image
Rows: album_id, album_image_id
我的专辑模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Album extends Model
{
public function albumImages(){
return $this->belongsToMany('App\AlbumImage', 'album_album_image','album_id','album_image_id');
}
}
我的AlbumImage模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class AlbumImage extends Model
{
public function album(){
return $this->belongsToMany('App\Album', 'album_album_image','album_image_id','album_id');
}
}
将$ images变量发送到我的specificAlbum视图的函数:
public function specificAlbum($albumName){
$images =
return view ('specificAlbum', ['images' => $images]);
}
现在我需要让$ images变量获取与专辑名称$ albumName相关联的所有图像。不幸的是,我似乎无法弄明白。任何帮助将不胜感激。
答案 0 :(得分:2)
在相册模型中定义图像关系
class Album extends Model
{
public function images(){
return $this->belongsToMany('App\AlbumImage', 'album_album_image','album_id','album_image_id');
}
}
然后:
public function specificAlbum($albumName)
{
$album = Album::with('images')->where('name', '=', $albumName)->firstOrFail();
return view ('specificAlbum', ['images' => $album->images]);
}