微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从刀片中的外键获取数据

如何解决从刀片中的外键获取数据

我不知道如何从这个外键中获取数据。我已按照文档中的所有步骤进行操作,但我仍然不知道需要做什么。

这是我的产品型号:

<?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');
    }
}

这是我的部门模型:

<?PHP

namespace App;

use Illuminate\Database\Eloquent\Model;

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

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

这是我的控制器(只有索引):

<?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'));
    }

这是我的观点(只有感兴趣的部分):

@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

        --}}

解决方法

这里

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

sectors 必须与函数名称 sector 相同

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

别的,foreign_key的默认值必须是product_id而不是products_id, 所以你必须在关系中定义它

 public function sector(){
        return $this->hasOne('App\Sector','products_id');
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。