删除 Eloquent 条记录之间的关系
Remove relationship between Eloquent records
我创建了两个 类 扩展 Eloquent(联系人和标签),它们具有多对多关系。我正在尝试创建取消标记联系人的方法,但无法找到任何文档来说明如何在不删除标签本身或联系人的情况下删除关系-table 中的条目。
到目前为止,我已经尝试过
$contact = Contact::find($contact_id);
$tag = $contact->tags->where('id', '=', $id);
$tag->delete();
这只会删除联系人。它不起作用是有道理的,但我不确定还能尝试什么。我不想删除联系人或标签,只是删除两者之间的关系。
我现在也试过了:
$tag = Tag::find($id);
$tag->contacts->detach($contact_id);
这给了我错误:
BadMethodCallException in Builder.php line 2071: Call to undefined
method Illuminate\Database\Query\Builder::detach()
以及
$tag = Tag::find($id);
$contact = $tag->contacts->find($contact_id);
$tag->contacts->detach($contact);
这给了我错误:
FatalErrorException in Tag.php line 34: Call to undefined method
Illuminate\Database\Eloquent\Collection::detach()
联系人和标签 类 扩展 Illuminate\Database\Eloquent\Model;
您可以使用 detach
建立多对多关系
http://laravel.com/docs/5.1/eloquent-relationships#inserting-many-to-many-relationships
您只需传入标签的ID。注意"tags"
后面的括号
$contact->tags()->detach($id);
因为它是多对多的,你也可以反过来
$tag->contacts()->detach($contact_id);
同样,您可以使用 attach
来创建关系。只是猜测,因为您不知道分离,您可能也可以使用附加。 Attach 可以采用单个 ID 或 ID 数组(加上一些更高级的选项)
$contact->tags()->attach($id);
$contact->tags()->attach([$id1, $id2, ...]);
我创建了两个 类 扩展 Eloquent(联系人和标签),它们具有多对多关系。我正在尝试创建取消标记联系人的方法,但无法找到任何文档来说明如何在不删除标签本身或联系人的情况下删除关系-table 中的条目。
到目前为止,我已经尝试过
$contact = Contact::find($contact_id);
$tag = $contact->tags->where('id', '=', $id);
$tag->delete();
这只会删除联系人。它不起作用是有道理的,但我不确定还能尝试什么。我不想删除联系人或标签,只是删除两者之间的关系。
我现在也试过了:
$tag = Tag::find($id);
$tag->contacts->detach($contact_id);
这给了我错误:
BadMethodCallException in Builder.php line 2071: Call to undefined method Illuminate\Database\Query\Builder::detach()
以及
$tag = Tag::find($id);
$contact = $tag->contacts->find($contact_id);
$tag->contacts->detach($contact);
这给了我错误:
FatalErrorException in Tag.php line 34: Call to undefined method Illuminate\Database\Eloquent\Collection::detach()
联系人和标签 类 扩展 Illuminate\Database\Eloquent\Model;
您可以使用 detach
建立多对多关系
http://laravel.com/docs/5.1/eloquent-relationships#inserting-many-to-many-relationships
您只需传入标签的ID。注意"tags"
后面的括号$contact->tags()->detach($id);
因为它是多对多的,你也可以反过来
$tag->contacts()->detach($contact_id);
同样,您可以使用 attach
来创建关系。只是猜测,因为您不知道分离,您可能也可以使用附加。 Attach 可以采用单个 ID 或 ID 数组(加上一些更高级的选项)
$contact->tags()->attach($id);
$contact->tags()->attach([$id1, $id2, ...]);