[英]Remove relationship between Eloquent records
I've created two classes extending Eloquent (contacts and tags), they have a ManyToMany relationship. 我创建了两个扩展Eloquent(联系人和标签)的类,它们具有ManyToMany关系。 I'm trying to create the method for un-tagging a contact, but am unable to find any documentation to tell how to remove the entry in the relation-table without deleting either the tag itself or the contact.
我正在尝试创建取消标记联系人的方法,但是无法找到任何文档来告诉如何删除关系表中的条目而不删除标记本身或联系人。
So far, I've tried 到目前为止,我已经尝试过了
$contact = Contact::find($contact_id);
$tag = $contact->tags->where('id', '=', $id);
$tag->delete();
This only deletes the contact. 这只会删除联系人。 It makes sense that it doesn't work, but I'm not sure what else to try.
它有意义,它不起作用,但我不知道还有什么可以尝试。 I don't want to delete the contact or the tag, just the relationship between the two.
我不想删除联系人或标签,只是两者之间的关系。
I've also now tried: 我现在也尝试过:
$tag = Tag::find($id);
$tag->contacts->detach($contact_id);
This gives me the error: 这给了我错误:
BadMethodCallException in Builder.php line 2071: Call to undefined method Illuminate\\Database\\Query\\Builder::detach()
Builder.php第2071行中的BadMethodCallException:调用未定义的方法Illuminate \\ Database \\ Query \\ Builder :: detach()
as well as 以及
$tag = Tag::find($id);
$contact = $tag->contacts->find($contact_id);
$tag->contacts->detach($contact);
This gives me the error: 这给了我错误:
FatalErrorException in Tag.php line 34: Call to undefined method Illuminate\\Database\\Eloquent\\Collection::detach()
Tag.php第34行中的FatalErrorException:调用未定义的方法Illuminate \\ Database \\ Eloquent \\ Collection :: detach()
Both the Contacts and Tags classes extend Illuminate\\Database\\Eloquent\\Model; Contacts和Tags类都扩展了Illuminate \\ Database \\ Eloquent \\ Model;
You can use detach
for many-to-many relationships 您可以使用
detach
来实现多对多关系
http://laravel.com/docs/5.1/eloquent-relationships#inserting-many-to-many-relationships http://laravel.com/docs/5.1/eloquent-relationships#inserting-many-to-many-relationships
You just pass in the ID of the Tag. 您只需传入标签的ID即可。 Take note of the parentheses after "tags"
记下“标签”后面的括号
$contact->tags()->detach($id);
Since it's many-to-many you could do the reverse as well 因为它是多对多的,你也可以反过来做
$tag->contacts()->detach($contact_id);
Similarly, you can use attach
to create relationships. 同样,您可以使用
attach
来创建关系。 Just guessing since you didn't know about detach that you probably could use attach as well. 只是猜测,因为你不知道分离,你可能也可以使用附加。 Attach can take a single ID or an array of IDs (plus some more advanced options)
Attach可以使用单个ID或ID数组(以及一些更高级的选项)
$contact->tags()->attach($id);
$contact->tags()->attach([$id1, $id2, ...]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.