Php Laravel 5-雄辩的关系返回空白
这是我第一次尝试雄辩的人际关系。我已经看过多个教程了 我有两张桌子。专辑和艺术家。一个艺术家可以有很多专辑。一张专辑只能有一位艺术家 下面是这两种模式的两个模式和模型 艺术家模型Php Laravel 5-雄辩的关系返回空白,php,laravel,laravel-5,laravel-5.1,Php,Laravel,Laravel 5,Laravel 5.1,这是我第一次尝试雄辩的人际关系。我已经看过多个教程了 我有两张桌子。专辑和艺术家。一个艺术家可以有很多专辑。一张专辑只能有一位艺术家 下面是这两种模式的两个模式和模型 艺术家模型 <?php namespace App; use Illuminate\Database\Eloquent\Model; class Artist extends Model { /** * The database table used by the model. *
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Artist extends Model
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'Artists';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['artist_name', 'artist_image_loc', 'followers'];
public function albums()
{
return $this->hasOne('App\Album');
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Album extends Model
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'Albums';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['album_name', 'album_image_loc', 'artist_id'];
public function artists()
{
return $this->belongsTo('App\Artist');
}
}
我需要找出为什么这些都是空的
谢谢你的帮助!
托比如果你说一个艺术家可以有很多专辑,那么,在艺术家课上你应该有:
public function albums()
{
return $this->hasMany('App\Album');
}
public function artist()
{
return $this->hasOne('App\Artist');
}
而且,如果一张专辑只能有一位艺术家,那么在专辑类中,您应该有以下内容:
public function albums()
{
return $this->hasMany('App\Album');
}
public function artist()
{
return $this->hasOne('App\Artist');
}
在你的代码中,你做的正好相反
要从相册中检索艺术家,您只需执行以下操作:
$album->artist;
要从艺术家那里检索专辑,请执行以下操作:
$artist->albums;
因此,您不需要调用该方法,您可以使用eloquent的动态属性(在本例中为艺术家和专辑)
您可以在此处找到更多信息:
$artist->albums;