雄辩模型属于在 L4 中不起作用的关系


Eloquent model belongsTo relationship not working in L4

我有以下表格:

用户

    Schema::create('users', function(Blueprint $table)
    {
        $table->increments('id');
        $table->string('username', 30);
        $table->string('email')->unique();
        $table->string('password', 60);
        $table->string('remember_token')->nullable();
        $table->timestamps();
    });

组织

    Schema::create('organisations', function(Blueprint $table)
    {
        $table->increments('id');
        $table->string('name')->unique('name');
        $table->integer('owner_id')->unsigned()->index()->nullable();
        $table->foreign('owner_id')->references('id')->on('users');
        $table->timestamps();
    });

我有以下组织雄辩模型:

class Organisation extends Eloquent {
    /**
     * @return 'Illuminate'Database'Eloquent'Relations'HasOne
     */
    public function owner()
    {
        return $this->belongsTo('User', 'owner_id', 'id');
    }
}

在我的控制器上,我加载所有organisations并将其传递给视图,如下所示:

public function index()
{
    return View::make('organisations.index')
        ->with('organisations', Organisation::all());
}

在我看来,当我尝试像这样显示数据时:

@foreach($organisations as $organisation)
    <div>
        Name : {{  $organisation->name }}
        <br>
        Owner: {{ $organisation->owner()->email }}
    </div>
@endofreach

当我这样做时,我得到一个对象是null例外。

我也尝试使用hasOne关系,但也没有奏效。

知道我可能在这里做错了什么吗?

试试这个:

@foreach($organisations as $organisation)
    <div>
        Name : {{  $organisation->name }}
        <br>
        Owner: {{ $organisation->owner->email }}
    </div>
@endforeach

没有所有者的()。这样,你会得到一个模型''用户对象,而不是一个属于对象。BelongsTo 对象不包含任何用户信息,但允许您添加更雄辩的方法来筛选查询。