简体   繁体   中英

Get data from foreign key in blade

I don't know how to get the data from this foreign key. I have followed all steps from the documentation, but I still don't know what needs to be done.

This is my product model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    public function sector(){
        return $this->hasOne('App\Sector');
    }
    public function sale(){
        return $this->hasOne('App\Sale');
    }
}

This is my Sector Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Sector extends Model
{
    protected $primaryKey = 'products_id';

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

This is my controller (only index):

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Product;
use App\Sector;
class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
       $products = Product::all();
       return view('worker.index', compact('products'));
    }

And this is my view (only the interested part):

@foreach ($products as $product)
    <div class="card" style="width: 18rem;">
        <div class="card-body">
        <h5 class="card-title">{{$product->name}}</h5>
        <p class="card-text">{{$product->codice_prodotto}}</p>

        {{-- <p class="card-text">{{$product->sectors->products_id}}</p> i've tried this and that gets' me this error
        Trying to get property 'products_id' of non-object         --}}

        {{-- <p class="card-text">{{$product->sectors['products_id']}}</p> i've tried this and that get's me this error
        Trying to access array offset on value of type null

        --}}

Here

{{$product->sectors->products_id}}

sectors must be sector the same of function name

{{$product->sector->products_id}}

Something else, the default of foreign_key must be product_id not products_id , so you have to define it in the relation

 public function sector(){
        return $this->hasOne('App\Sector','products_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