Laravel 5 - 雄辩的关系空无一人

时间:2015-09-20 21:36:19

标签: 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.
     *
     * @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');
    }
}

我有一张专辑和一位艺术家坐在数据库中,专辑的artist_id设置为艺术家的ID。

>>> $album = new App\Album;
=> App\Album {#694}
>>> $album->artists()->get()
=> Illuminate\Database\Eloquent\Collection {#704
     all: [],
   }

我需要找出为什么这些都是空的。

感谢您的帮助! 托比

0 个答案:

没有答案