abu abu
abu abu

Reputation: 7028

Relationship in Laravel-5.6

I have three tables like below.

posts
    _id   - integer
    name - string

sentences
    _id      - integer
    post_id - integer
    name    - string

translations (word by word)
    _id          - integer
    post_id     - integer
    sentence_id - integer
    word_id     - integer
    name        - string

In PostController.php I am trying to fetch data like below

return Post::with(['sentences', 'sentences.translations'])->limit(2)->get();

I have function in post.php model is like below

protected $primaryKey = '_id';
public function sentences()
{
    return $this->hasMany('App\Model\sentence', 'post_id','_id');
}

I have function in sentences.php model is like below

protected $primaryKey = '_id';
public function translations()
{
    return $this->hasMany('App\Model\translation', 'sentence_id','_id');
}

I would like to fetch posts along with sentences and translations.

I can fetch post and sentences but I am facing issue while I am trying to fetch translations.

I am getting all the translations which sentence_id is matched with idof sentences table, but post_id is not matching with the current post id of post table.

Upvotes: 0

Views: 46

Answers (1)

Brian Lee
Brian Lee

Reputation: 18187

If you've named your primary keys any thing other than id, you need to set the primary key name on each model:

class Post extends Model {
    protected $primaryKey = '_id';
}

Match your relations to the correct name also:

return $this->hasMany(Sentence::class, 'post_id','_id');

Upvotes: 1

Related Questions