小编Est*_*ern的帖子

Laravel whereHas 多对多关系

我有两个具有多对多关系的主表和一个数据透视表。

模型“类型”

    public function attributes()
    {
        return $this->belongsToMany('App\Attribute', 'attribute_type');
    }
Run Code Online (Sandbox Code Playgroud)

模型“属性”

    public function types()
    {
        return $this->belongsToMany('App\Type', 'attribute_type');
    }
Run Code Online (Sandbox Code Playgroud)

数据透视表“attribute_type”

    Schema::create('attribute_type', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('type_id')->unsigned();
        $table->foreign('type_id')->references('id')->on('types');
        $table->integer('attribute_id')->unsigned();
        $table->foreign('attribute_id')->references('id')->on('attributes');
    });
Run Code Online (Sandbox Code Playgroud)

我想以随机顺序显示 5 个属于 id < 10 类型的属性。

$attributes = Attribute::whereHas('types', function ($query) {
            $query->where('id', '<', '10');
        })->orderByRaw("RAND()")->limit(5);
Run Code Online (Sandbox Code Playgroud)

例如

$attribute->id
Run Code Online (Sandbox Code Playgroud)

给我“未定义的属性:Illuminate\Database\Eloquent\Builder::$id”

php many-to-many relationships laravel eloquent

5
推荐指数
2
解决办法
2万
查看次数

Laravel - 多对多

我有两个具有多对多关系的主表和一个数据透视表。

表格

型号产品

public function orders()
{
    return $this->belongsToMany('App\Order');
}
Run Code Online (Sandbox Code Playgroud)

型号订购

public function products()
{
    return $this->belongsToMany('App\Product', 'OrderDetails');
}
Run Code Online (Sandbox Code Playgroud)

$orders = Equipment::all();

@foreach($orders as $order)
    @foreach($order->products as $product)
        {!! $product->name !!} //it works
        // How to print the value of the quantity?
    @endforeach
@endforeach
Run Code Online (Sandbox Code Playgroud)

我应该怎么做才能打印数量的值?

php database many-to-many relationship laravel

4
推荐指数
1
解决办法
863
查看次数