use*_*910 5 php polymorphic-associations laravel eloquent
我有这样的模型:
<?php
class Post extends Eloquent {
protected $fillable = [];
public function photos()
{
return $this->morphMany('Upload', 'imageable');
}
public function attachments()
{
return $this->morphMany('Upload', 'attachable');
}
}
Run Code Online (Sandbox Code Playgroud)
我的morphMany
表的架构是这样的:
CREATE TABLE `uploads` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`raw_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`size` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`downloads` int(11) NOT NULL DEFAULT '0',
`imageable_id` int(11) DEFAULT NULL,
`imageable_type` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
`attachable_id` int(11) DEFAULT NULL,
`attachable_type` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
`user_id` int(10) unsigned NOT NULL,
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`),
KEY `uploads_user_id_index` (`user_id`),
CONSTRAINT `uploads_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `posts` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=45 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Run Code Online (Sandbox Code Playgroud)
现在我需要删除此表的一行,我尝试$posts->photos()->delete();
但删除了与此相关的所有行Post
.
有人能帮助我吗?
pat*_*cus 13
$posts->photos()
是用于返回帖子的所有照片的关系查询.如果你打电话delete()
,它将删除所有这些记录.如果您只想删除特定记录,则需要确保只在要删除的记录上调用delete.例如:
$posts->photos()->where('id', '=', 1)->delete();
Run Code Online (Sandbox Code Playgroud)
小智 8
要从多对多多态关系中的数据透视表中删除,只需使用分离:
$posts->photos($photoModel)->detach();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8541 次 |
最近记录: |