Laravel 5.5关系

时间:2018-03-22 20:04:22

标签: laravel laravel-5 laravel-5.5

我试图实现模特之间的关系,并且我接受了#34;试图获得财产'产品'非对象"而且我不明白为什么,因为我之前以同样的方式使用过它并且它工作得很好。

  

关系的逻辑是1商家有很多产品

这是我正在使用的代码:

商家模特:

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

}

产品型号:

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

}

这是ProductController中的方法:

public function merchantProducts() {

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

如果有人可以帮助我,我会非常感激。

提前致谢!!

2 个答案:

答案 0 :(得分:0)

假设商家不保证存在于提供商家ID的数据库中,最好检查商家是否存在,如果是,则检索其产品。

$products = collect();
$merchant = Merchant::find($merchant_id);
if($merchant) {
    $products = $merchant->products;
}
return $products;

答案 1 :(得分:0)

所有!!

最后我用这种方式使用资源解决了这个问题:

public function merchantProducts(Request $request) {

        $merchant_id = $request->merchant_id;

        $products = Product::where('merchant_id', $merchant_id)->paginate(15);

        return ProductResource::collection($products);

    }

感谢所有!!

相关问题