dongtao5055 2015-07-23 16:01
浏览 1024

在Laravel的多对多关系中使用'with'

I have a table user - User(Model), which has relationship:

public function roles()
    {
        return $this->belongsToMany(Config::get('entrust.role'), Config::get('entrust.role_user_table'), 'user_id', 'role_id');
    }

public function regions() {

        return $this->belongsToMany('App\Regions', 'user_region', 'user_id', 'region_id');
    }

I am trying this query, but it doesn't me the required result

$result = User::with(['roles' => function($query) {
                                $query->select('user_id','role_id');
                                }, 
                                'regions' => function($query) {
                                $query->select('user_id','region_id', 'region_name');
                                }])
                                ->where('user_id', '=', $id)
                                ->get()->toArray();

It only gives me data from user table and doesn't give the relationship data.

What am I missing out??

  • 写回答

3条回答 默认 最新

  • duanchao5258 2015-07-23 17:21
    关注

    The notation you are using should be used for constraints. From your code it seems you don't actually need any contraints.

    $result = User::with(['roles', 'regions'])
                                    ->where('user_id', '=', $id)
                                    ->first()->toArray();
    

    The relationship you defined is only a belongsTo. You should probably use a hasMany relationship.

    评论

报告相同问题?

悬赏问题

  • ¥15 蓝桥oj3931,请问我错在哪里
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染