简体   繁体   中英

laravel get foreign key data

I have controller

public function orders()
{
    return view('user.dashboard', ['order' => orders::where('user_id', Auth::id())->get(),]);
}

Code above prints out all orders from orders table based on user's id.

Orders table as well has product id column, which has a foreign key that links to products table.

The problem is I want to print out product name based on product id, but I don't know how.

If you have stablished your relations correctly,

Class Order extends Model{

   public function products(){
     return $this->hasMany(Product::class);
   }
}

Then in your controller

public function orders()
{
    return view('user.dashboard', ['order' => orders::with('products')->where('user_id', Auth::id())->get(),]);
}

Thus in every order you will have a collection with all products in that order.

Alternatively you load only those data needed in your view as the name of the product

public function orders()
{
    return view('user.dashboard', ['order' => orders::with('products.name')->where('user_id', Auth::id())->get(),]);
}

Read more about eager loading in Laravel Doc

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