我現在需要使用3個DB表格。一個domains-table,一個tags-table和一個pivot-table。在我的數據透視表中,只有兩個「主表」中的兩個foreign_keys。 domains_id
和tags_id
是兩個外鍵。使用Laravel編輯pivot平板電腦?
我跟着這個頁面上的介紹就在這裏: http://laraveldaily.com/pivot-tables-and-many-to-many-relationships/
,但我還是不明白「管理許多一對多的關係:附連 - 分離同步」的一部分。
的標籤我的控制器代碼:
$id = Input::get('id');
$request = $request->tagging;
$tags = explode(',', $request);
$all_tags = [];
foreach ($tags as $tag) {
$tag = trim($tag); // entfernen von leerstellen
$friendly_tags = Str::slug($tag); // user friendly tags
if (Str::length($friendly_tags)) {
$all_tags[] = Tags_Domains::create([ 'name' => $friendly_tags ]);
}
}
$domain = Domains::query()->findOrFail($id);
$domain->tags()->saveMany($all_tags);
在我越來越域ID的函數的第一行。這個ID應該保存在我的數據透視表中的domains_id屬性中。
在這一行之後,我格式化用戶想要添加的標籤並將它們保存到我的$ all_tags數組中。例如:
$all_tags = [sunny', 'fitness', 'healthy'];
現在,我與它們保存在我的標籤表:
Tags_Domains::insert($all_tags);
現在,我要保存這些標籤的ID在我的透視表中的tags_id屬性。我仍然不知道這是怎麼回事。 laravel doc。並沒有真正的幫助。
我在我的標籤模型realation:
public function domains() { return $this->belongsToMany('App\Models\technical\Domains', 'domain_tag', 'id', 'domains_id'); }
我realation在我的域模型:
public function tags() { return $this->belongsToMany('App\Models\technical\Tags_Domains', 'domain_tag', 'id', 'tags_id'); }
你不需要Tags_Domains模型,你應該只需要多對一標籤和領域模型。定義了多對多關係。看看文檔https://laravel.com/docs/5.1/eloquent-relationships#many-to-many –
我已經添加了我的問題。我刪除了樞軸模型,並將我問題底部的一行添加到我的域模型中。 - 但我仍然不太明白如何使用.. – WellNo