Y
Y
Yury Bondaruk2022-03-03 01:11:14
PHP
Yury Bondaruk, 2022-03-03 01:11:14

How to get username using Eloquent ORM?

There is the following scheme: Post - User
From the post we get the value of author (user id) and this value must be passed to the Users table, displaying the nickname. How I did it:

Post.php model

public function author() {
        return $this->belongsTo(User::class);
    }


Model User.php

public function post() {
        return $this->hasMany(Post::class);
    }


I'm trying to get a nickname:

I found another solution, but it looks suboptimal for this task, I want to implement it through table links.

$author = User::where('id', $post['author'])->first();


Table with users:
621fec2711c1b937574404.jpeg
Table with entries:
621fec79e70ad202839436.jpeg

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yury Bondaruk, 2022-03-03
@drnkwtr

Solution: it was necessary to specify foreignkey 'author' and ownerkey 'id' :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question