jeudi 22 mars 2018

Laravel 5.5 Relationships

I'm trying to implement relationships between models and i recieve "Trying to get property 'products' of non-object" and i don't understand why, because i used this before in the same way and it's worked fine.

The logic of relationship is that 1 Merchant hasMany Products

this is the code that i'm using:

Merchant Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Merchant extends Model {
    protected $table = "merchants";

    protected $fillable = [
        'merchant_id', 'merchant_name', 'secret_key', 'merchant_address', 'merchant_phone', 'merchant_admin',
        'merchant_contact', 'merchant_mail', 'merchant_description', 'enable', 'created_at', 'updated_at'];

    public function users() {

        //many to many
        return $this->belongsToMany('App\User');
    }

    public function branchOffices() {
        return $this->hasMany('App\BranchOffice', 'merchant_id', 'merchant_id');
    }

    public function products() {
        return $this->hasMany('App\Products', 'merchant_id', 'merchant_id');
    }

    public function transactions() {
        return $this->hasMany('App\Transaction', 'merchant_id', 'merchant_id');
    }

    public function readers() {
        return $this->hasMany('App\Reader', 'merchant_id', 'merchant_id');
    }

}

Product Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model {
    protected $table = "products";

    protected $fillable = [
        'id', 'barcode', 'description', 'price', 'currency_id', 'merchant_id', 'branch_id',
        'enable', 'created_at', 'updated_at'];

    public function merchants() {
        return $this->belongsTo('App\Merchant', 'merchant_id', 'merchant_id');
    }

    public function currencies() {
        return $this->belongsTo('App\Currency', 'iso_4712', 'currency_id');
    }

    public function branch_sectors() {
        return $this->belongsToMany('App\BranchSector');
    }

}

And this is the method in ProductController:

public function merchantProducts() {

        $products = Merchant::find('merchant_id')->products;
        return $products;
    }

If someone can help me i'll be very thankfull.

Thanks in advance!!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire