Laravel - 删除整个集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38120305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel - delete whole collection
提问by Marco
I have images for articles, and when I am updating article I would like to check if the images are the same, if not I would like to delete them but if it is possible I would like to delete the whole collection without another query, something like what I have in the code below $images->delete();
.
This is my function:
我有文章的图像,当我更新文章时,我想检查图像是否相同,如果不是,我想删除它们,但如果可能的话,我想删除整个集合,而无需其他查询,某事就像我在下面的代码中所拥有的一样$images->delete();
。这是我的功能:
$images = Media::where('article_id', $article->id)->get();
foreach($images as $image) {
$article_images[] = $image->original_name;
}
foreach($files as $file) {
$filePathArr = explode('/', $file);
$fileName = array_pop($filePathArr);
$originalFile = explode('-', $fileName);
$originalFileName = array_pop($originalFile);
$newFiles[] = $originalFileName;
}
if ($newFiles != $article_images){
$images->delete();
}
回答by Sigismund
You just can't delete from database without making a query.
您不能在不进行查询的情况下从数据库中删除。
You will have to make new request like this:
您将不得不像这样提出新的请求:
Media::where('article_id', $article->id)->delete();
It's just one simple query, so there shouldn't be any performance penalty.
这只是一个简单的查询,因此不应该有任何性能损失。
If we are talking about collection with 100's of items, you can optimize the query like this:
如果我们谈论的是包含 100 个项目的集合,您可以像这样优化查询:
Media::whereIn('id', $images->pluck('id'))->delete();
回答by MCFreddie777
If you have your Models linked, you can.
如果您已链接模型,则可以。
Class Exercise.php:
课堂练习.php:
/**
* Exercise belongs to exactly one lecture
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function lecture()
{
return $this->belongsTo('\App\Lecture');
}
and Class Lecture.php:
和 Class Lecture.php:
/**
* Gets all the exercises asociated to this lecture
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function exercises()
{
return $this->hasMany('\App\Exercise');
}
Then you can in your controller simply do:
然后你可以在你的控制器中简单地做:
public function delete($id, DeleteLectureRequest $request)
{
$lecture = Lecture::findOrFail($id);
$lecture->exercises()->delete(); // easy
}
(Imagine that your Article == my Lecture, and your Media == my Exerises)
(想象一下你的文章==我的讲座,你的媒体==我的练习)
Of course, at first you have to set properly foreign keys in your DB and link your Models that way.
当然,首先您必须在您的数据库中正确设置外键并以这种方式链接您的模型。