Laravel属于不工作

时间:2017-05-02 08:03:00

标签: php laravel laravel-5 laravel-4 eloquent

这应该很简单,但我不知道有什么不对。我有以下迁移。 create_players_table

public function up()
    {
        Schema::create('players', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('club_id');
            $table->string('first_name');
            $table->string('last_name');
            $table->double('price', 3, 2);
            $table->enum('position', ['goalkeeper','defender','Midfielder','Striker']);
            $table->timestamps();
        });
    }

create_clubs_table

public function up()
    {
        Schema::create('clubs', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('location');
            $table->timestamps();
        });
    }

这种关系是直接的,因为一个球员有一个球队(一对一),一个球队可以有很多球员(一对多)。问题是我想列出所有球员与他们各自的球队,但不知何故我最终得到错误。这是我的玩家模型。

class Player extends Model
{
  public function club()
    {
        return $this->belongsTo('App\Club');
    }
}

这是控制器:

public function index()
{
    $players=Player::find(1);
    echo $players->club()->location;
}

我收到此错误

TeamController.php第15行中的ErrorException:未定义属性:Illuminate \ Database \ Eloquent \ Relations \ BelongsTo :: $ name

任何帮助将不胜感激......

4 个答案:

答案 0 :(得分:0)

你的关系不是真正的数据库关系试着让你像这样的关系:

    public function up()
{
    Schema::create('players', function (Blueprint $table) {
        $table->increments('id');

        $table->unsignedInteger('club_id');
        $table->foreign('club_id')->references('id')->on('clubs');

        $table->string('first_name');
        $table->string('last_name');
        $table->double('price', 3, 2);
        $table->enum('position', ['goalkeeper','defender','Midfielder','Striker']);
        $table->timestamps();
    });
}

https://laravel.com/docs/5.4/migrations#foreign-key-constraints

答案 1 :(得分:0)

它应该是这样的:

$players=Player::with('club')->find(1);
echo $players->club->location;

答案 2 :(得分:0)

玩家模型

class Player extends Model
{
  public function club()
    {
        return $this->belongsTo('App\Club', 'club_id', 'id');
    }
}

播放器控制器

public function index()
{
    $players=Player::find(1);
    echo $players->club->location;
}

答案 3 :(得分:0)

()

中不使用->club()
public function index()
{
    $players=Player::find(1);
    echo $players->club->location;
}

正如错误所说,它指的是" BelongsTo"关系。即这里->club()返回关系对象,而不是俱乐部对象。如果您想将俱乐部对象调用为$players->club->location;