call method in the Laravel query

Asked

Viewed 141 times

3

I have this query here:

SELECT p.descr, p.dt_hr, f.id_friend
FROM users u
JOIN friends f ON u.id = f.id_user
JOIN posts p ON p.id_user = f.id_friend
WHERE u.id = 1

She returns it to me:

inserir a descrição da imagem aqui

I’m wanting to spin on the foreach and mount an array more or less like this:

[0] => [
    'descr' => $ln['descr'],<br>
    'dt_hr' => $ln['dt_hr'],<br> 
    'name' => $this->getNameByIdFriend($ln['id_friend']) // pegar o nome desse usuário
]

ai in this method "getNameByIdFriend", I would select in another table picking the id I passed to return the name to my position name of my array.

I do this way using Zend Framework 2, wanted to know how I can do with the Framework.

Thank you!

  • 1

    Which table is the name? If it is in the Friend table you can return it straight instead of returning the id: SELECT p.descr, p.dt_hr, f. name, if it is not, you can give one more Join of the Friend table, to the other containing the name and put in select

  • In itself inner join you solve this, make the junction of where search the name, because there will have an ideal performance, already the other in each selected item do a search in the bank would be a big mistake, even have a form with a search at once, but even so with inner join is the best way to solve this problem.

  • The name is in the table users(id,name), table Friends(id, id_user, id_friend). I could not yet, it is bringing the name related to my Where.

  • I managed to solve:

  • It looks like this: SELECT p.descr,p.dt_hr, (SELECT U1.name FROM users U1 WHERE U1.id = f.id_friend) AS name FROM Friends f JOIN users u ON u.id = f.id_user JOIN posts p ON p.id_user = f.id_friend WHERE u.id = 1 ORDER BY p.dt_hr DESC

1 answer

0

Using the Query Builder of Laravel, your query should look like this:

DB::table('users')
    ->select('posts.descr, posts.dt_hr, friends.name')
    ->join('friends', 'users.id', '=', 'friends.id_user')
    ->join('posts', 'friends.id_friend', '=', 'posts.id_user')
    ->where('users.id', 1)
    ->get();

You must receive one Collection containing the results as objects of the Stdclass class.

(The table is supposed to friends have the column name.)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.