php laravel set deleted_at has problem with subqueries [duplicate]

bvn4nwqk  于 11个月前  发布在  PHP
关注(0)|答案(2)|浏览(73)

此问题已在此处有答案

How to use a sub_query with a table that has soft delete?(1个答案)
8小时前关闭
首先,我在我的laravel应用程序中有 repositoriesservices

主要问题

我的主要问题是laravel与子查询不兼容,不能很好地支持它们!

*我使用以下版本:

  • Laravel v10.16.1
  • php 8.1
    *我有deleted_atupdated_atcreated_at

deleted_at问题

如果我使用软删除trait并希望deleted_at自动处理,当我使用下面的子查询时,它会显示错误:

class UserRepository {
    ...

    public function getWhere(array $columns, Builder $where)
    {
        $query = $this->model
            ->newQuery()
            ->when($where, function (Builder $query) use ($where) {
                $query->fromSub($where, 'sub');
            });

        return $query->get($columns);
    }

    ...
}

个字符

问题查询示例

SELECT * FROM (SELECT * FROM `users` WHERE `name`='john') AS `sub` WHERE `users`.`deleted_at` IS NULL


在上面的查询中,deleted_at不存在,但它存在于数据库中,这是因为子查询别名。
我搜索了一下,似乎是laravel的问题,最后我删除了自动软删除,并手动操作,如下所示:

class UserRepository {
    ...
    
    public function getWhere(array $columns, Builder $where)
    {
        $prefix = $this->model->getTable();
        $query = $this->model
            ->newQuery()
            ->when($where, function (Builder $query) use ($where, &$prefix) {
                $prefix = 'sub';
                $query->fromSub($where, $prefix);
            });

        $query->whereNull($prefix . '.deleted_at');

        return $query->get($columns);
    }

    ...
}

我该怎么办?

(希望我的解释可以理解)

  • 先谢谢你 *

编辑

我改变了我的例子,因为我做错了update操作和updated_at在我的情况下是没有问题的,但子查询和设置deleted_at有问题。

hsvhsicv

hsvhsicv1#

好的,通常当你用$table->softDeletes();创建一个Schema时,它会自动在表中创建deleted_at列。所以我不知道为什么deleted_at不存在。
模式的一个示例如下所示。

public function up()
{
    Schema::create('able_name', function (Blueprint $table) {
        $table->id();
        $table->softDeletes();  // This adds the deleted_at column
    });
}

字符串
在此之后,您必须运行迁移。如果是第一次运行php artisan migrate,则放弃所有并重新运行php artisan migrate:fresh
同样,当使用use use SoftDeletes;时,它将自动为所有查询添加全局范围,例如 * 其中deleted_at为null。

如果你按照给定的顺序使用它,这将像一块蛋糕一样工作。没有什么是错的,就这么简单

要以其他方式修复问题,您可以将withoutTrashed()添加到查询中。

public function getWhere(array $columns, Builder $where)
{
    $query = $this->model
        ->newQuery()
        ->withoutTrashed()
        ->when($where, function (Builder $query) use ($where) {
            $query->fromSub($where, 'sub');
        });

    return $query->get($columns);
}

  • 但是考虑我的第一个建议,因为这是正确的处理方式,你不必为此付出额外的努力。
xpcnnkqh

xpcnnkqh2#

我不太明白你想干什么,但我想我能帮你
你可以试试这个

$query = yourModelName::where('name' , 'john')->get();

字符串
来制作这个

SELECT * FROM (SELECT * FROM `users` WHERE `name`='john') AS `sub` WHERE `users`.`deleted_at` IS NULL


如果你想在laravel中绑定一个外键到一个主键,试试这个
将此添加到“用户”模型

public function post(){
    return $this->hasMany(Post::class);
}


并将其添加到其他模型“帖子”中

public function user(){
    return $this->belongsTo(User::class);
}


然后你可以从这两张table上得到你想要的任何东西

$post[0]->title //title of post table
$post[0]->user->name //name of user table

相关问题