Eloquent 使用 "LIKE" 语句的查询在 Laravel 6 中不起作用

Eloquent query with "LIKE" statement doesn't work in Laravel 6

我正在尝试制作一个用户搜索引擎,该引擎使用字符串将其与集合中每个用户的用户名进行比较,return 那些将该字符串作为其用户名的子字符串的搜索引擎我的 Laravel 项目中有一个与自身相关的 User 模型,这是与 follower_followed 枢轴 table 的 many to many 关系,这个 table s是通过迁移生成的,两种迁移的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 方法 return 所有 followed 用户都通过 lazy eager loading 加载,无论方法参数字符串如何,如果我取消注释注释此方法内的行我得到异常 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 %%)。我希望我的意图是明确的。

我试过 但没用。

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

提前致谢。

$user->load(["followed" => function($query) use ($username) { $query->where('username', 'LIKE', "%{$username}%"); } ]);

希望能帮到你轻松