简体   繁体   English

Laravel - 如何访问和操作 Pivot 表

[英]Laravel - How to Access and Manipulate Pivot Table

I have two tables, users and like_categories which has many-to-many relationship.我有两个表,用户和 like_categories 具有多对多关系。 The pivot table is called like_category_user. pivot 表称为like_category_user。 After inserting two users data into the db, here is my pivot table look like: https://i.imgur.com/MeeRbiV.png将两个用户数据插入数据库后,这是我的 pivot 表,如下所示: https://i.imgur.com/MeeRbiV.png

Im a little bit confused on how can i access the pivot table since I didnt create a custom model for that pivot table.我对如何访问 pivot 表有点困惑,因为我没有为 pivot 表创建自定义 model。 I want to count the amount for each of the different like category for each user and store it in object array like this:我想为每个用户计算每个不同的同类类别的数量,并将其存储在 object 数组中,如下所示:

[
    {
        "User Id": 1,
        "Like Categories": [
            {
                "Category": Chinese Restaurant
                "Amount": 1
            },
            {
                "Category": Korean Restaurant
                "Amount": 2
            },
            {
                "Category": Fast Food Restaurant
                "Amount": 3
            },
            {
                "Category": Italian Restaurant
                "Amount": 1
            },
            {
                "Category": Steakhouse Restaurant
                "Amount": 3
            }
        ]
    },
    {
        "User Id": 2,
        "Like Categories": [
            {
                "Category": Thai Restaurant
                "Amount": 1
            },
            {
                "Category": Kebab Shop
                "Amount": 3
            },
            {
                "Category": Pizza Place
                "Amount": 2
            },
            {
                "Category": Steakhouse
                "Amount": 1
            }
        }
    }
]

My process method:我的处理方法:

public function showUserLikesData() {
    //
}

Try following this explanation , according to your code.根据您的代码,尝试遵循此说明

There is no real need to create a model for this table.没有必要为此表创建 model。 Basically you will need to create a function in your models to have access to this table.基本上,您需要在模型中创建 function 才能访问此表。 In your view's or your api, you will need to mention this function along with Pivot, but the field.在您的视图或您的 api 中,您需要提及此 function 以及 Pivot,但该字段。 Something like:就像是:

$showUserLikesData->pivot->FieldName

In your relationship you can add ->withPivot('column_name') , which allows you to use more than foreign keys from the pivot table.在您的关系中,您可以添加->withPivot('column_name') ,它允许您使用 pivot 表中的多个外键。 So, an example:所以,举个例子:

public function things(){
    return $this->belongsToMany('App\ModelName')->withPivot('column_name')->withTimestamps();
}

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

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