我正在尝试使用Laravel创建多对多关系,但我卡住了。
这是我的当前表模型:
相册(album)
我想从albumxuser_image表中获取专辑名称。
目前我已经做了以下工作。
Album.php模型
routes.php(我没有使用视图,因为我正在练习)
这是我得到的错误信息。
这是我的当前表模型:
相册(album)
album_id
name
created_at
用户图像
user_image_id
value
相册用户图片(连接表)
albumxuser_image_id (primary key & auto increment)
album_id (FK from album)
user_image_id (FK from user_image)
我想从albumxuser_image表中获取专辑名称。
目前我已经做了以下工作。
Album.php模型
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Album extends Model {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'album';
protected $primaryKey = 'album_id';
public function AlbumxUserImage() {
return $this->belongsToMany('AlbumxUserImage', 'albumxuser_image','album_id','user_image_id');
}
}
routes.php(我没有使用视图,因为我正在练习)
Route::get('all', function() {
$albumxuserimage = AlbumxUserImage::all();
foreach ($albumxuserimage->AlbumxUserImage as $getthem) {
echo $getthem->pivot->name; // I want to get the name column of the album table.
}
});
AlbumxUserImage.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class AlbumxUserImage extends Model {
protected $table = 'albumxuser_image';
protected $primaryKey = 'albumxuser_image_id';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['album_id', 'user_image_id'];
}
这是我得到的错误信息。
Call to undefined method Illuminate\Database\Eloquent\Collection::AlbumxUserImage()
AlbumxUserImage
模型吗?我们能看一下吗? - BrokenBinary