首页 文章

在laravel中的集合中获取透视列

提问于
浏览
0

如何用枢轴列返回雄辩模型的集合?例如,用户和大桶之间存在M:N关系 . 我想检索所有用户数据(使用vats和pivot列(costOfDelivery),它位于数据透视表user_vat中) .

在我的代码中,我有:

$vats = Vat::whereHas('users', function($query) use ($user) {
                $query->where('user_id', $user->id);
     })->with('country')
            ->get();

但是这从vats和country返回数据,而不是来自数据透视表“user_vat”,如何检索还是costOfDelivery?

2 回答

  • 0

    要从数据透视表中检索数据,必须使用pivot属性

    像这样的东西

    foreach($users->roles as $role){
        echo $role->pivot->created_at;
    }
    

    要返回json,可以使用 toJson() 方法

    $vat->toJson();
    
  • 1
    <?php
    
    /**
     * The model class with the belongsToMany user class relation.
     */
    class Vat extends Model
    {
        public function user() 
        {
             return $this->belongsToMany(\App\User::class)
                 ->withPivot(['cost_of_delivery', /**Specific columns for the pivot.*/]);  
        }
    
    }
    

    <?php
    
    /*
     * Your query (which I think is a little bit complicated that it should be.
     */
    $vats = Vat::whereHas('users', function($query) use ($user) {
                $query->where('user_id', $user->id);
     })->with(['country', 'users'])
            ->get();
    

    我会用的 . 喜欢:

    <?php
    $user->load(['vats.country']);
    $vats = $user->getRelationValue('vats');
    

    $vats->first()->pivot->cost_of_delivery
    

    应该给你第一桶的交付成本 .

相关问题