带有“LIKE”语句的雄辩查询在 Laravel 6 中不起作用

Posted

技术标签:

【中文标题】带有“LIKE”语句的雄辩查询在 Laravel 6 中不起作用【英文标题】:Eloquent query with "LIKE" statement doesn't work in Laravel 6 【发布时间】:2020-12-04 21:48:56 【问题描述】:

我正在尝试创建一个用户搜索引擎,该引擎使用字符串将其与集合中每个用户的用户名进行比较,并返回那些具有该字符串作为其用户名子字符串的用户,并且我有一个 @987654323 @model 在我的Laravel 项目中与自身相关,这是与follower_followed 数据透视表的many to many 关系,这些表是通过迁移生成的,两种迁移的up 方法如下所示。

up method inside create_users_table migration.

public function up()
    Schema::create('users', function (Blueprint $table) 
        $table->bigIncrements("id");
        $table->string("username", 15);
        $table->string("name", 35);
        $table->string("lastname", 35);
        $table->string("country", 35)->nullable();
        $table->string("city", 35)->nullable();
        $table->string("phone_number", 35)->nullable();
        $table->string("email", 35)->unique();
        $table->string('biography', 120)->nullable();
        $table->string("password", 255);
        $table->bigInteger("role_id")->unsigned()->default(1);
        $table->timestamp("email_verified_at")->nullable();
        $table->rememberToken();
        $table->softDeletes();
        $table->timestamps();
   );

up method inside create_follower_followed_table migration.

public function up()
    Schema::create('follower_followed', function (Blueprint $table) 
        $table->bigIncrements('id');
        $table->bigInteger("follower_id")->unsigned();
        $table->bigInteger("followed_id")->unsigned();
        $table->foreign("follower_id")->references("id")->on("users")->onDelete("cascade");
        $table->foreign("followed_id")->references("id")->on("users")->onDelete("cascade");
        $table->timestamps();
    );

现在,这些关系在 User 模型中定义如下。

User model.

namespace App;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements JWTSubject

    use Notifiable;

    protected $fillable = [
        "role_id",
        "username",
        "name",
        "lastname",
        "country",
        "city",
        "phone_number",
        "email",
        "password",
        "biography"
    ];
    
    protected $hidden = [
        "role_id",
        "password",
        "remember_token",
        "email_verified_at",
        "deleted_at",
        "created_at",
        "updated_at"
    ];
    
    protected $casts = [
        "email_verified_at" => "datetime",
    ];
    
    protected $appends = [
        "following"
    ];
    
    protected $with = ["profile_picture"];
    
    public function getFollowingAttribute()
        return DB::table("follower_followed")
            ->where("follower_id", Auth::user()->id)
            ->where("followed_id", $this->attributes["id"])
            ->exists();
    
    
    public function getJWTIdentifier()
        return $this->getKey();
    
    
    public function getJWTCustomClaims()
        return [];
    
    
    public function getRouteKeyName()
        return "username";
    
    
    public function role()
        return $this->belongsTo(Role::class);
    
    
    public function profile_picture()
        return $this->hasOne(UserProfilePicture::class);
    
    
    public function followers()
        return $this->belongsToMany(User::class, "follower_followed", "followed_id", "follower_id");
    
    
    public function followed()
        return $this->belongsToMany(User::class, "follower_followed", "follower_id", "followed_id");
    

最后我在我的UserController 中有以下方法。

UserController

public function searchFollowed($username)
    
    $user = Auth::user();
    
    $user->load([
        "followed" => function($query)
            global $username;
            $query
                // ->select(["id", "usename", "name", "lastname"])
                ->where("username", "like", "%$username%");
         
     ]);
     
    return response()->json($user->followed);

它与api.php路由文件中定义的以下路由有关。

Route::group(["namespace" => "API"], function()
    Route::get("search_followed/username", "UserController@searchFollowed");

所有这些都无法正常工作,因为searchFollowed 方法返回所有通过lazy eager loading 加载的followed 用户,无论方法参数字符串也是如此,如果我取消注释此方法中的注释行,我得到异常SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in field list is ambiguous (SQL: select `id`, `usename`, `name`, `lastname`, `follower_followed`.`follower_id` as `pivot_follower_id`, `follower_followed`.`followed_id` as `pivot_followed_id` from `users` inner join `follower_followed` on `users`.`id` = `follower_followed`.`followed_id` where `follower_followed`.`follower_id` in (1) and `username` like %%) .我希望我的意图很明确。

我试过this,但没有用。

有人可以帮我解决这个问题吗?

提前致谢。

【问题讨论】:

->where('username', 'LIKE', "%$username%") 这样使用 我已经做到了...我把reference. dd($query); 的输出是什么? $user->load(["followed" => function($query) use ($username) $query->where('username', 'LIKE', "%$username %"); ]); => 像这样使用 @AnkitaDobariya 哇...干得好,谢谢! 【参考方案1】:
$user->load(["followed" => function($query) use ($username)  $query->where('username', 'LIKE', "%$username%");  ]);

希望它对你有帮助

【讨论】:

我不需要"%$username%" 中的花括号。

以上是关于带有“LIKE”语句的雄辩查询在 Laravel 6 中不起作用的主要内容,如果未能解决你的问题,请参考以下文章

Laravel 雄辩的复杂搜索查询问题

Laravel 4,雄辩 - 语句和运算符之间

如何在 Laravel 中使用 LIKE 语句使用查询结果并再次查询

Laravel - 真的很难理解雄辩

Laravel:如何设置带有条件的自定义列?

雄辩的选择语句给了我一个错误