spoon
4 years ago

Eloquent many to many relationships

Posted 4 years ago by spoon

Hi,

I have a basic problem. Last week I've asked a similar question but I stuck again.

person = person table
thing = book table
bookxauthor = junction table (person_id and thing_id are foreign keys)

I'm trying to get a book's authors using a book's id, but my count() echoes 0. It works when I change the order of person_id and thing_id in the relationships.

Can someone explain why it happens?

$author = Thing::FindorFail($id)->person;
            echo $author->count();

Here are my models.

Thing.php
<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Thing  {

  /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'thing';
    protected $primaryKey = 'thing_id';


    public function person() {
        return $this->belongsToMany('\App\Models\Person', 'bookxauthor','thing_id','person_id');
    }
}

Person.php

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;


class Person extends Model {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'person';
    protected $primaryKey = 'person_id';

    protected $fillable = ['person_name', 'alsoknownas', 'formalname', 'bornin', 'bornwhere', 'height', 'about'];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */

    public function thing() {
        return $this->belongsToMany('\App\Models\Thing', 'bookxauthor','thing_id','person_id');
    }
}

BookxAuthor.php

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;


class BookxAuthor extends Model {

    protected $table = 'bookxauthor';
    protected $primaryKey = 'bookxauthor_id';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['person_id', 'thing_id'];

}

Please sign in or create an account to participate in this conversation.