Hi, is there any way to combine "with" and "join" in a single fluent query? Eg.:
Post::with('categories')
->leftJoin('post_author as pa', 'pa.post_id', '=', 'posts.id')
->get();
This code would return all posts but with the "categories" array empty. However this code:
Post::with('categories')
->get();
would return posts WITH categories.
Is there any way to get posts with categories using the first query?
(There are reasons for using leftJoin. I know I could create Post->Author eloquent relationship, but the real query is quite complex and using selectRaw.)
Thanks
Try specifying column names in ->get()
Something like
Post::with('categories')
->leftJoin('post_author as pa', 'pa.post_id', '=', 'posts.id')
->get(['categories.name', 'posts.text', 'post_author.name']);
This results in columns not found. I just don't understand why it ignores everything within the with() function when you add join to eloquent query.
Similar query is working for me :/ But i think it has something to do with same column names/values (like IDs, etc...) and eloquent cant handle it... but i may be off
I had a similar issue. Maybe looking at my thread will shed some light on your problem: http://laravel.io/forum/12-11-2014-eloquent-confused-about-which-id-column-to-use-when-using-a-join-with-eager-loading
@VenomRush Exactly - if you join tables in Eloquent, always specify the columns to select, otherwise Eloquent will get confused and will give you unexpected results. Even if it doesn't look like at first glance.
Just had the same problem. When you add the select(['post.*']) method it will work. Seems like the internals get a bit confused. This was my first hit on Google, thats why i dropped the solution here :-).
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community