【发布时间】:2015-11-10 15:30:34
【问题描述】:
我正在尝试使用 Laravel 创建多对多关系,但我被卡住了。
这是我当前的表格模型:
专辑
album_id
name
created_at
用户图像
user_image_id
value
albumxuser_image(连接表)
albumxuser_image_id (primary key & auto increment)
album_id (FK from album)
user_image_id (FK from user_image)
我希望能够从 albumxuser_image 表中获取专辑名称。
这是我到目前为止所做的。
相册.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(我在练习,所以没用view)
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型号吗?我们能看到吗? -
为什么不直接从
Album模型中获取专辑名称?为什么要先查找枢轴?
标签: php laravel eloquent laravel-5.1