简体   繁体   中英

Eloquent ORM Many-to-many relationship

I've just started using Eloquent ORM (Without Laravel) and I am having issues with the many to many relationships. I have a table where I store Families (Article categories), another one for the Articles , and a third one as a "pivot". I want to be able to get all the articles a Family has, and all the families an article belongs to. So I have coded this models.

Families

class Families extends Model {

public $table = 'Families';

    public function Articles() {
        return $this->belongsToMany('Articles', 'articles_families', 'families_id', 'articles_id');
    }

}

Articles

class Articles extends Model {

public $table = 'Articles';

     public function Families() {
         return $this->belongsToMany('Families', null, 'articles_id', 'families_id');
     }

}

Then I am trying to retrieve the data like this:

$families = Families::all();
echo $families[1]->Articles;

However, it just returns an empty array, when it should return a couple of articles. I have tripled checked that all the values are correct in the three tables. If I echo the Eloquent query debugger I can see that it is looking for a null value and I'm pretty sure that's the problem, but I don't quite know how to fix it. Here:

{"query":"select * from `Families`","bindings":[],"time":49.13},{"query":"select `Articles`.*, `articles_families`.`families_id` as `pivot_families_id`, `articles_families`.`articles_id` as `pivot_articles_id` from `Articles` inner join `articles_families` on `Articles`.`id` = `articles_families`.`articles_id` where `articles_families`.`families_id` is null","bindings":[],"time":38.93}

The null value is at the end of the last query.

I just found the solution myself. As my primary key columns are called Id , and Eloquent by default assumes the primary key is called id , I needed to override that by adding a class property protected $primaryKey = "Id"; and it now retrieves the data properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM