Farzad
Farzad

Reputation: 57

Laravel 5.4 belongsToMany relationship returns empty

In Laravel 5.4 I'am trying to set up a Many To Many Relation. but the belongsToMany returns empty! Here's my migrations and models.

botusers Table:

public function up()
{
    Schema::create('botusers', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('t_id');
        $table->string('first_name');
        $table->string('last_name');
        $table->string('username');
        $table->string('mobile');
        $table->timestamps();
    });
}

candidates Table:

public function up()
{
    Schema::create('candidates', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('token');
        $table->string('degree');
        $table->integer('age');
        $table->text('desc');
        $table->string('photo_url');
        $table->string('cv_url');
        $table->timestamps();
    });
}

Third table, botuser_candidate Table:

public function up()
{
    Schema::create('botuser_candidate', function (Blueprint $table) {
        $table->integer('botuser_id');
        $table->integer('candidate_id');
    });
}

and the votes() method in Botuser Model:

public function votes()
{
    return $this->belongsToMany(Candidate::class)->get();
}

When I fire the votes() method returns an empty array. and I also tested bellow method too,

public function votes()
{
    return $this->belongsToMany(Candidate::class,'botuser_candidate','botuser_id','candidate_id')->get();
}

What I missed here? What should I do?

Edit: I also added the foreign keys to the relation but the result is still same!

Upvotes: 0

Views: 3250

Answers (1)

oseintow
oseintow

Reputation: 7371

I would suggest you remove the get() method on the belongsToMany

Then query the database with

$c=new App\Candidate; 
$c->with('votes')->get()

if you still want to use $c->votes() then you would have to do some changes to your functions. Lets use scope to achieve it.

public function candidates()
{
    return $this->belongsToMany(Candidate::class,'botuser_candidate','botuser_id','candidate_id');
}

public function scopeVotes($query)
{
   return $query->with("candidates")->get();
}

Then now we can call $v->votes() and it should return all your record.

Calling get() directly on belongsToMany method will return empty array.

Upvotes: 1

Related Questions