简体   繁体   中英

Retrieving eloquent relationship with laravel

When I try to get the name of the Category from my product, I discovered I had to use a 'C' rather than a 'c' before it retrieved results. However when I try to get the Supplier name, the lowercase s works just fine. I was wondering what is causing this difference. Also if I dd($var), is the relations field expected to be empty. I assumed it would have something related to the relationships defined in my models.

Blade.php

  <td>{{$product->Category->name}}</td>
     <td>{{$product->salePrice}}</td>
     <td>{{$product->stock}}</td>
 <td>{{$product->supplier->company_name}}</td>

Product.php

 public function category()
    {
        return $this->belongsTo('App\Category','category');
    }
 public function supplier()
    {
        return $this->belongsTo('App\Supplier','supplier_id');
    }

Category.php

public function product()
    {
        return $this->hasMany('App\Product');
    }  

Supplier.php

public function product()
    {
        return $this->hasMany('App\Product');
    }

You're missing a _id on your Product model:

public function category()
{
    return $this->belongsTo('App\Category','category_id');
}

Or leave empty

public function category()
{
    return $this->belongsTo('App\Category');
}

In your Controller

public function index()
{
  $products = Product::all()->with('category');
  return view('your_view', compact('products'));
}

If you dd the products In your View you will se that the relation has been loaded because of the

Eager Loading

When accessing Eloquent relationships as properties, the relationship data is "lazy loaded". This means the relationship data is not actually loaded until you first access the property. However, Eloquent can "eager load" relationships at the time you query the parent model.

@foreach($products as $product)
<td>{{$product->category->name}}</td>
     <td>{{$product->salePrice}}</td>
     <td>{{$product->stock}}</td>
 <td>{{$product->supplier->company_name}}</td>
@endforeach

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