简体   繁体   English

Select * 来自 laravel 中的 pivot 表

[英]Select * from a pivot table in laravel

I have a many to many relation with table users,items and the pivot table user_item and i need to call the query: Select * from user_item where user_id=$user->id in laravel and return the results in json format. I have a many to many relation with table users,items and the pivot table user_item and i need to call the query: Select * from user_item where user_id=$user->id in laravel and return the results in json format. I try with我尝试

$user=User::find(session('user_id'))->items()->get();
return response ()->json($user);

But it doesn't work.但它不起作用。 How can I do that?我怎样才能做到这一点?

class User extends Authenticatable {
    
    public function items (){
            return $this->belongsToMany ("App\Models\Item", "user_item", "user", "item");
    }
}
class Item extends Models {
    
    public function users (){
        return $this->belongsToMany ("App\Models\User", "user_item", "item", "user");
    }
}

You can define columns in your pivote table using withpivot method您可以使用withpivot方法在数据透视表中定义列

public function items (){
        return $this->belongsToMany ("App\Models\Item", "user_item", 
    "user", "item")->withPivot(['column1', 'column2','another_column']);
}

to get relation instead of using get() , you should use like below:要获取关系而不是使用get() ,您应该使用如下:

$user=User::find(session('user_id'))->items;
return response ()->json($user);

above will give below json result:以上将给出以下 json 结果:

[{
    "id": 4,
    "name": "PC",
    "pivot": {
        "column1": 1,
        "column2": 4,
        "another_column": "2016-03-03"
    }
},
{
    "id": 5,
    "name": "Phone",
    "pivot": {
        "column1": 1,
        "column2": 4,
        "another_column": "2016-03-03"
    }
}]

you can also include pivot in use user model using with():您还可以使用 with() 将 pivot 包含在用户 model 中:

$user=User::with('items')->find(session('user_id'));
return response ()->json($user);

give json result something like:给 json 结果类似于:

{
    "id": 1,
    "name": "User Name",
    "email": "email@user.com",
    "created_at": null,
    "updated_at": null,
    "items": [{
        "id": 4,
        "name": "PC",
        "pivot": {
            "column1": 1,
            "column2": 4,
            "another_column": "2016-03-03"
        }
    },
      {
        "id": 5,
        "name": "Phone",
        "pivot": {
            "column1": 1,
            "column2": 4,
            "another_column": "2016-03-03"
        }
    }]
}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM