简体   繁体   中英

Display user name from another table Laravel 8

Hellow guys, so I have 2 tables

  1. is Listings
  2. is Users

in Listings I have some columns, one is user_id, and is related to users tables. I want to display the user name related to the user table. in the index blade, I use some tags. But when I use ->rightjoin("users", "users.id", "=", "listings.user_id") it's works but, the join broke my tags make them default, same with others posts.

 public function index(Request $request)
    {
        $listings = Listing::where('is_active', true)->with('tags') 
            //->rightjoin("users", "users.id", "=", "listings.user_id") //don't show tags of the posts
            ->orderBy('listings.created_at', 'desc')
            ->get();
                //check if posts ar listing by last date or something
$tags = Tag::orderBy('name') // variable displayed in view
            ->get();

You could just use the with method to get the related user like this

public function index(Request $request) {
        $listings = Listing::where('is_active', true)->with(['user', 'tags']) 
            ->orderBy('listings.created_at', 'desc')
            ->get();
}

but make sure that you add to your Listing model the correct relation like this

Listing Model


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

I recommend this code for controller:

public function index(Request $request) {
        return $listings = Listing::query()
            ->where('is_active', true)->with(['user', 'tags'])
            ->orderBy('listings.created_at', 'desc')
            ->get();
}

In the models section, I suggest you put this code:

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

I suggest you fill in the fields foreignKey, ownerkey in relation: as in the following example:

public function user()
{
    return $this->belongsTo(User::class, 'user_id', 'id');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM