[英]Laravel 5 - Eloquent relationships returning empty
這是我第一次嘗試雄辯的人際關系。 我已經看過多個教程了。
我有兩張桌子。 專輯和藝術家。 一個藝術家可以有很多專輯。 一張專輯只能有一個藝術家。
這是這兩個的兩個模式和模型。
藝術家模型
<?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');
}
}
藝術家架構
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateArtistsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('Artists', function (Blueprint $table) {
$table->increments('id');
$table->string('artist_name');
$table->string('artist_image_loc');
$table->integer('followers');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('Artists');
}
}
專輯架構
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAlbumsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('Albums', function (Blueprint $table) {
$table->increments('id');
$table->string('album_name');
$table->string('album_image_loc');
$table->integer('artist_id')->unsigned();
$table->timestamps();
$table->foreign('artist_id')
->references('id')
->on('Artists');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('Albums');
}
}
我有一張專輯和一位藝術家坐在數據庫中,專輯的藝術家 ID 設置為藝術家的 ID。
>>> $album = new App\Album;
=> App\Album {#694}
>>> $album->artists()->get()
=> Illuminate\Database\Eloquent\Collection {#704
all: [],
}
我需要找出為什么這些返回空。
謝謝你的幫助! 托比
如果你說一個藝術家可以有很多專輯,那么在藝術家類中你應該有這個:
public function albums()
{
return $this->hasMany('App\Album');
}
而且,如果一張專輯只能有一個藝術家,那么在專輯類中你應該有這個:
public function artist()
{
return $this->hasOne('App\Artist');
}
在你的代碼上你做了相反的事情。
要從專輯中檢索藝術家,您只需執行以下操作:
$album->artist;
並從藝術家那里檢索專輯:
$artist->albums;
所以,你不需要調用該方法,你可以使用 eloquent 的動態屬性(在這種情況下,藝術家和專輯)你可以在這里找到更多信息: http : //laravel.com/docs/5.1/eloquent-relationships
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.