dimanche 28 août 2016

Eloquent ORM returns null using with() eager load

When using Eloquent's with() the eager loaded data sometimes becomes null. In my case, I have three tables, Users, Blogposts and Categories. The blogposts table has two foreign keys, called author and category. The query performed is given by

return Blogpost::with(['author', 'category'])->get();

The response is, well, odd. Note that author becomes null from id: 3 and category from id: 4.

In reality both the ids 1, 3 have the same author (superuser) as do the ids 2, 4 (steve). Also id 1, 4 have the same category (web dev).

It seems as if a/an category/author is already retrived and bounded to a blogpost the past categories/authors becomes null.

[
  {
    id: 4,
    author: null,
    image_name: "banner1.png",
    category: null,
    intro: "Hello World!",
  },

  {
    id: 3,
    author: null,
    image_name: "banner1.png",
    category: {
        id: 3,
        name: "big data",
    },
    intro: "Hello World!",
  },

  {
    id: 2,
    author: {
        id: 2,
        email: "foo@foo.foo",
        fullname: "foo foo",
        is_admin: false,
    },
    image_name: "banner1.png",
    category: {
        id: 2,
        name: "science",
    },
    intro: "Hello World!",
  },

  {
    id: 1,
    author: {
        id: 1,
        email: "superuser@superuser.com",
        fullname: "superuser superuser",
        is_admin: true,
    },
    image_name: "banner1.png",
    category: {
        id: 1,
        name: "web dev",
    },
    intro: "Hello World!",
  }
]

Finally here are the relations defined in the models

// User model
public function blogposts() {
    return $this->hasMany('App\Blogpost', 'id');
}

// Blogpost model
public function author() {
  return $this->belongsTo('App\User', 'id');
}

public function category() {
  return $this->belongsTo('App\Category', 'id');
}

// Category model
public function blogposts() {
  return $this->hasMany('App\Blogpost', 'id');
}

Is there any explanation to this?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire