【问题标题】:laravel relation with informationlaravel 与信息的关系
【发布时间】:2017-09-21 04:52:58
【问题描述】:

我有 products 表和 countries 表,它们假设彼此之间存在多对多关系,但包含关系的附加参数。

所以在产品中有产品ID,名称

在国家/地区有国家/地区ID,名称

product_country中有country_id、product_id、price

产品型号:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;


class Product extends Model
{
    /**
    * Get the countries for the product.
    */
    public function countries()
    {
        return $this->belongsToMany('Country');
    }

}

国家模式:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;


class Country extends Model
{
    /**
    * Get the countries for the product.
    */
    public function products()
    {
        return $this->belongsToMany('Product');
    }

}

所以我知道我可以使用 ->withPivot('价格') 将其添加到枢轴关系中,但我无法弄清楚 - 例如按国家/地区查询产品列表的最佳方法是什么,也许我的结构是错误的,但我希望最终能够获得所有产品当然是针对特定国家/地区的价格。

感觉我需要做很多工作才能按国家/地区为产品定价。

Country::find(1)->products->first()->pivot->price

【问题讨论】:

    标签: php laravel eloquent many-to-many


    【解决方案1】:

    先把这个关系函数改成Country.php

     public function products()
        {
            return $this->belongsToMany(Product::class,'pivot_table_name','country_id','product_id')->withPivot('price','sku');
        }  
    

    然后尝试这个查询。

     $countries = Country::with(['products'])->get();
    

    如果你想传递参数然后使用这个查询

     $countries = Country::with([
                    'products' => function ($query) use ($productId) {
                        $query->where('id', $productId);
                    }
                ])->where('id', $countryId)->first();
    

    【讨论】:

    • 是的,我的例子有效,它和你做的完全一样,我不是说我只是想让它更容易和更聪明。所以这就是我所说的我知道我能做的,但这不是我想做的……我的目标是:给出一个产品 _id 和一个 country_id -> 用他的所有参数获取产品..,这是不仅仅是价格,它是运费、货币、sku 等...我希望能够对产品表与产品国家表进行“内部连接”,所以我将从产品 -> id、名称、价格中获取,运输等..按国家/地区ID。
    • @ShahafAntwarg 您在关系函数中传递了多个列。像 withPivot('column1', 'column2');
    猜你喜欢
    • 2014-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-31
    • 2018-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多