我想在 Laravel 中创建一个功能

发布于 2025-01-10 13:16:57 字数 541 浏览 0 评论 0原文

我想在 Laravel 上创建一个功能来检查数据库表的行是否存在。检查后,根据检查结果,应删除、添加新列或跳过它们。

foreach($this->category_product as $k => $item) {
        $category_product = CategoryProduct::where([['category_id', $this->category_id],['product_id', $k]])->firstOr(function () {
                $category_product = CategoryProduct::create([
                        'category_id' => $this->category_id,
                        'product_id' => $k
                ]);
        });
}

这是我到目前为止所拥有的。如何删除查询中不存在的行? 任何帮助将不胜感激。 谢谢

I want to create a functionality on Laravel that would check the rows of a database table for existence. After checking, depending on the results of the check, it should delete, add new columns or skip them.

foreach($this->category_product as $k => $item) {
        $category_product = CategoryProduct::where([['category_id', $this->category_id],['product_id', $k]])->firstOr(function () {
                $category_product = CategoryProduct::create([
                        'category_id' => $this->category_id,
                        'product_id' => $k
                ]);
        });
}

Here's what I have so far. How to remove rows that do not exist in a query?
Any help would be appreciated.
Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

黯然#的苍凉 2025-01-17 13:16:57

我希望我理解正确,因为问题不够清楚,但这里有一种删除行(如果存在)的方法:

注意:您缺少 use ($k)

foreach ($this->category_product as $k => $item) {
    $category_product = CategoryProduct::where([
        ['category_id', $this->category_id],
        ['product_id', $k]
    ])->firstOr(function () use ($k) {
        // Delete if it exists.
        CategoryProduct::where([
            'category_id' => $this->category_id,
            'product_id' => $k
        ])->delete();

        // Create if it doesn't exist.
        $category_product = CategoryProduct::create([
            'category_id' => $this->category_id,
            'product_id' => $k
        ]);

    });
}

I hope I understood you right, as the question isn't clear enough, but here is a way to delete the rows if they exist:

Note: you were missing use ($k)

foreach ($this->category_product as $k => $item) {
    $category_product = CategoryProduct::where([
        ['category_id', $this->category_id],
        ['product_id', $k]
    ])->firstOr(function () use ($k) {
        // Delete if it exists.
        CategoryProduct::where([
            'category_id' => $this->category_id,
            'product_id' => $k
        ])->delete();

        // Create if it doesn't exist.
        $category_product = CategoryProduct::create([
            'category_id' => $this->category_id,
            'product_id' => $k
        ]);

    });
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文