我有以下表使用Schema
小號創建的:在Laravel與鋒關係處理5.3
Schema::create('typen', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
});
Schema::create('auktionen', function (Blueprint $table) {
$table->increments('id');
$table->integer('typ')->unsigned();
$table->foreign('typ')->references('id')->on('typen');
});
typen
僅在創建一次該表包含固定值:
Typen
id| name
1 | Typ 1
2 | Typ 2
...
這些值是恆定的,在應用程序生命週期內不會再添加更多內容。所以我創建的每個Auktion
都應該與一個Typ
關聯。 我爲Auktion
創建了模型,並將其視爲一對一的關係(這是否正確?)。
我想創建一個使用雄辯查詢,這樣給定的典型的Auktion:
$thetyp = App\Typ::where("id", "=", 1)->first();
$auktion->typ()->associate($thetyp);
,並獲取我的Auktion
的Typ
的name
:
$auktion->typ->name;
目前我的模型看起來像這樣的Auktion
:
public function typ()
{
return $this->hasOne('App\Typ', 'typ');
}
這是行不通的。我已經嘗試設置不同的關係,但(使用save()
的時候 - 我真的不希望)我只是在不同的錯誤代碼,從不確定的方法(associate()
的錯誤,其中一個SQL語句失敗嘗試更新我的typen
表結束。
有人能澄清這個問題我解釋一下我必須使用哪種關係?
EDIT1:作爲調用
$thetyp = App\Typ::where("id", "=", 1)->first();
$auktion->typ()->save($thetyp);
和
Trying to get property of non-object
調用
$auktion->typ->name;
時,當評論我已經在
Auktion
模型
public function typ()
{
return $this->belongsTo('App\Typ', 'typ');
}
導致Undefined property: App\Auktion::$typ
使用belongsTo
試圖提到
EDIT2:
我只是想通
echo $auktion->typ()->first()->name;
確實工作。 But referring to this answer這應該是相同的
echo $auktion->typ->name;
我究竟做錯了什麼?
EDIT3:
我使用建議的代碼嘗試:
$thetyp = App\Typ::find($typ);
$auktion->typ->save($thetyp);
後,我導航到該視圖ehere我跑我得到這個代碼:
我今天第二次得到這個,從哪裏冒出來
請看我的回答。希望能幫助到你! – idelara