0

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.

7
  • What issue are you facing? Do you mean Post::with('sentences.translations')->get()? Commented Jul 13, 2018 at 13:18
  • 1
    Your translations relationship is correct, but somehow Laravel uses it with different columns. Commented Jul 13, 2018 at 15:32
  • You haven't overridden the getForeign function in the sentence model have you? Commented Jul 13, 2018 at 21:57
  • Thanks @JonasStaudenmeir. I edited my post. Commented Jul 14, 2018 at 4:21
  • 1
    Are your primary keys named _id? Commented Jul 14, 2018 at 4:37

1 Answer 1

1

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');
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @DigitalDrifter. Actually I set the primary key name on each model like this protected $primaryKey = '_id'; but I forgot to mention here. My issue is like this ... I am getting all the translations which sentence_id is matched with id of sentences table, but post_id is not matching with the current post id of post table.
In that case it seems you've correctly setup the relations, I'm curious what does $post->getForeignKey() return?
Thanks @DigitalDrifter. $post->getForeignKey() returns post_id. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.