B
B
BonBon Slick2017-02-10 15:40:55
Laravel
BonBon Slick, 2017-02-10 15:40:55

Get forum.name via thread.id in post column (table joins)?

The project is old, in the new version of Laravel you can set up a relation without any problems through Eloquent ORM. And here are the entries:

$posts = Post::orderBy('id', 'desc')
        ->join('threads', 'threads.id', '=', 'posts.thread_id')
        ->join('forums', 'forums.id', '=', 'threads.forum_id')
        ->join('users', 'users.id', '=', 'posts.user_id')
        ->select('posts.text', 'posts.id', 'posts.sticky', 'users.first_name', 'users.last_name', DB::raw('threads.name as thread_name'), DB::raw('threads.id as thread_id'), DB::raw('forums.name as forum_name'));

Here we extract all the posts, the topics to which they are attached, and the forums of their topics.
Now, we need to do the same only in relation to the 1st post.
I'm still rather weak with the joins, I'm trying to do something along the lines of:
$posty = Post::join('threads', 'threads.id', '=', 'posts.thread_id')
        ->join('forums', 'forums.id', '=', 'threads.forum_id')
        ->join('users', 'users.id', '=', 'posts.user_id')
        ->select('posts.text', 'posts.id', 'posts.sticky', 'users.first_name', 'users.last_name', DB::raw('threads.name as thread_name'), DB::raw('threads.id as thread_id'), DB::raw('forums.name as forum_name'));

        dd($posty->forum_name);

Will return an error:
Whoops, looks like something went wrong.

1/1
ErrorException in PostsController.php line 115:
Undefined property: Illuminate\Database\Eloquent\Builder::$forum_name
in PostsController.php line 115
at HandleExceptions->handleError(8, 'Undefined property: Illuminate\\Database\\Eloquent\\Builder::$forum_name', 'C:\\Users\\BonBonS\\Desktop\\OpenServer\\domains\\forum2\\app\\Http\\Controllers\\Admin\\PostsController.php', 115, array('post' => object(Post), 'posty' => object(Builder))) in PostsController.php line 115
at PostsController->edit(object(Post))
....

How to join correctly in this case?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
BonBon Slick, 2017-02-10
@BonBonSlick

Answer:

$posts = Post::orderBy('id', 'desc')
        ->join('threads', 'threads.id', '=', 'posts.thread_id')
        ->join('forums', 'forums.id', '=', 'threads.forum_id')
        ->join('users', 'users.id', '=', 'posts.user_id')
        ->select('posts.text', 'posts.id', 'posts.sticky', 'users.first_name', 'users.last_name', DB::raw('threads.name as thread_name'), DB::raw('threads.id as thread_id'), DB::raw('forums.name as forum_name'));
        $post = $posts->find($post->id);
        dd($post->forum_name);

S
Stanislav Pochepko, 2017-02-10
@DJZT

You need to learn the join hardware first, and then try to use them in laravel.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question