Jasmel Pc
Jasmel Pc

Reputation: 535

Relationships not working after setTable() in eloquent

Consider without using relation first,

    DB::connection()->enableQueryLog();
    $oPost = new Post();
    $oPost->setTable('posts_two');
    $aPost = $oPost->get();
    $queries = DB::getQueryLog();
    dd($queries);

This results the following query

select * from posts_two

Now , Consider the case with the relation,

    DB::connection()->enableQueryLog();
    $oPost = new Post();
    $oPost->setTable('posts_two');
    $aPost = $oPost->with('comments')->get();

    $queries = DB::getQueryLog();
    dd($queries);

This results the following query

select * from posts

The problem is , Whenever I use with(), It is taking default table (posts) instead of the table name which i set via setTable (posts_two)

I could not identify why this happens ? Advance thanks for any kind of help. :)

Upvotes: 1

Views: 128

Answers (1)

Casper
Casper

Reputation: 1539

get() is non static method beacuse of that you received,

select * from posts_two

However with() is static method. Static method uses brand new instance so they create new instance that will have default table property. Therefore you received,

select * from posts

According to my understanding you cannot use static method here therefore I think you have to fetch posts_two data first and after that you have to fetch comments using posts_two data and bind togehter.

Upvotes: 1

Related Questions