新增關聯(lián)模型

2018-02-24 15:52 更新

附加一個關聯(lián)模型

您常常會需要加入新的關聯(lián)模型。例如新增一個 comment 到 post 。除了手動設定模型的 post_id 外鍵,也可以從上層的 Post 模型新增關聯(lián)的 comment :

$comment = new Comment(['message' => 'A new comment.']);
$post = Post::find(1);
$comment = $post->comments()->save($comment);

上面的例子里,新增的 comment 模型中 post_id 字段會被自動設定。

如果想要同時新增很多關聯(lián)模型:

$comments = [
    new Comment(['message' => 'A new comment.']),
    new Comment(['message' => 'Another comment.']),
    new Comment(['message' => 'The latest comment.'])
];
$post = Post::find(1);
$post->comments()->saveMany($comments);

從屬關聯(lián)模型 ( Belongs To )

要更新 belongsTo 關聯(lián)時,可以使用 associate 方法。這個方法會設定子模型的外鍵:

$account = Account::find(10);
$user->account()->associate($account);
$user->save();

新增多對多關聯(lián)模型 ( Many To Many )

您也可以新增多對多的關聯(lián)模型。讓我們繼續(xù)使用 User 和 Role 模型作為例子。我們可以使用 attach 方法簡單地把 roles 附加給一個 user:

附加多對多模型

$user = User::find(1);
$user->roles()->attach(1);

也可以傳入要存在樞紐表中的屬性數(shù)組:

$user->roles()->attach(1, ['expires' => $expires]);

當然,有 attach 方法就會有相反的 detach 方法:

$user->roles()->detach(1);

attach 和 detach 都可以接受ID數(shù)組作為參數(shù):

$user = User::find(1);
$user->roles()->detach([1, 2, 3]);
$user->roles()->attach([1 => ['attribute1' => 'value1'], 2, 3]);

使用 Sync 方法同時附加一個以上多對多關聯(lián)

您也可以使用 sync 方法附加關聯(lián)模型。 sync 方法會把根據(jù) ID 數(shù)組把關聯(lián)存到樞紐表。附加完關聯(lián)后,樞紐表里的模型只會關聯(lián)到 ID 數(shù)組里的 id :

$user->roles()->sync([1, 2, 3]);

Sync 時在樞紐表加入額外數(shù)據(jù)

也可以在把每個 ID 加入樞紐表時,加入其他字段的數(shù)據(jù):

$user->roles()->sync([1 => ['expires' => true]]);

有時您可能想要使用一個命令,在建立新模型數(shù)據(jù)的同時附加關聯(lián)??梢允褂?save 方法達成目的:

$role = new Role(['name' => 'Editor']);
User::find(1)->roles()->save($role);

上面的例子里,新的 Role 模型對象會在儲存的同時關聯(lián)到 user 模型。也可以傳入屬性數(shù)組把數(shù)據(jù)加到關聯(lián)數(shù)據(jù)庫表:

User::find(1)->roles()->save($role, ['expires' => $expires]);
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號