[英]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
沒有所有者的()
。 這樣,您將獲得Model \\ User對象,而不是belongsTo對象。 BelongsTo對象不包含任何用戶信息,但允許您添加更多有效的方法來過濾查詢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.