Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

afoysal's avatar

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 below error

"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'translations.sentence_id_id' in 'where clause' (SQL: select * from `translations` where `translations`.`sentence_id_id` in (1, 2

0 likes
4 replies
staudenmeir's avatar

Why is the translations relationship different on Stack Overflow? Didn't you copy the lines from your codebase?

afoysal's avatar

Thanks @staudenmeir . I am trying with different options. I made post before in SO, then I tried again and made post here. Thanks.

Swaz's avatar

There's no need to define the $primaryKey variable. Also, you're calling a morphMany() relationship when it looks like another hasMany() to me.

posts
    id - integer

sentences
    id - integer
    post_id - integer

translations
    id - integer
    sentence_id - integer
class Post extends Model
{   
    public function sentences()
    {
        return $this->hasMany(Sentence::class);
    }
}
class Sentence extends Model
{   
    public function translations()
    {
        return $this->hasMany(Translation::class);
    }
}
Post::with('sentences.translations')->get();
1 like
afoysal's avatar

Thanks @Swaz . If I use your solution 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.

Please or to participate in this conversation.