Monday, April 3, 2017

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?



via WebCrawler

Advertisement