Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
515 views
in Technique[技术] by (71.8m points)

php - How to use DB::raw in eager loading

I'm currently using eager loading in laravel and used the select() method. However, when I tried to select the child table, it returns an error. Please see my code below.

Controller

$posts = Post::with('author');

$posts->select(['body', DB::raw('CONCAT(users.first_name, " ", users.last_name) as AUTHOR')]);

The code above returns this error:

Column not found: 1054 Unknown column 'users.first_name' in 'field list'

So I tried to make it like this:

$posts = Post::with('author');

$posts->select(['body', DB::raw('CONCAT(author.first_name, " ", author.last_name) as AUTHOR')]);

Now I used the relationship to get the first and last name but I'm getting the same error. Any idea?

UPDATE

I'm using laravel 5.2 for this project.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should be able to tackle this with:

$posts = Post::with('author:id,first_name,last_name')->get();

Based on laravel docs you have to provide the column names of the relationship table as above. Don't forget to Add the "id" as well because it will not work otherwise.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...