Home > Blockchain >  SQLSTATE[42S22]: Column not found: 1054 Unknown column 'teams.team_b_id' in 'where cl
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'teams.team_b_id' in 'where cl

Time:08-04

I have a competitions table and it has the following fields.

public function up()
{
    Schema::create('competitions', function (Blueprint $table) {
        $table->id();
        $table->foreignId('user_id')->constrained()->cascadeOnDelete();
        $table->foreignId('category_id')->constrained()->cascadeOnDelete();
        $table->foreignId('team_a_id')->constrained('teams')->cascadeOnDelete();
        $table->foreignId('team_b_id')->constrained('teams')->cascadeOnDelete();
        $table->string('date');
        $table->string('time');
        $table->string('league');
        $table->string('end_at');
        $table->string('live')->nullable();
        $table->timestamps();
    });
}

And I want to search team_a_id and team_b_id in the teams' table.

Competition.php

public function team()
{
    return $this->belongsTo(Team::class, 'team_a_id', 'team_b_id');
}

CompetitionController.php

public function index()
{
    $keyword = request('search') ?? null;
    $competitions = Competition::query()
        ->whereHas('team', function ($query) use ($keyword) {
            $query->where('title' , 'LIKE' , "%{$keyword}%");
        })->paginate(25);
    return view('Admin.competitions.index', compact('competitions'));
}

error

sql

CodePudding user response:

You must pass the primary key of the table teams here on the parameter 3:

public function team()
{
    return $this->belongsTo(Team::class, 'team_a_id', '**ID_TEAM**');
}

CodePudding user response:

The third parameter for BelongsTo is the Key in the other table ('id' as default), you can't do what you tried, the simplest solution would be to have 2 relationship, one for each team.

    public function teamA()
{
    return $this->belongsTo(Team::class, 'team_a_id';
}


    public function teamB()
{
    return $this->belongsTo(Team::class, 'team_b_id';
}

and do the same logic that you have now, but adding a OrWhereHas

$competitions = Competition::query()
->whereHas('teamA', function ($query) use ($keyword) {
            $query->where('title' , 'LIKE' , "%{$keyword}%");
        })
->orWhereHas('teamB', function ($query) use ($keyword) {
            $query->where('title' , 'LIKE' , "%{$keyword}%");
        })->paginate(25);
  • Related