简体   繁体   English

Laravel 5.3:多对多房地产的数据

[英]Laravel 5.3 : Many to many realtionship's data

I have ,many to many relationship between User and Project 我与UserProject之间有很多关系

Realtionship Names are : User model have projects and Project model have users . 房地产名称是: User模型具有projectsProject模型具有users And are correctly formed. 并正确形成。

I am using the following code for the data tables : 我在数据表中使用以下代码:

public function handleProjects(Request $request)
    {
        $responseData = \App\Misc::handleDatatable([
            "request" => $request,
            "model" => "\App\Project",
            "actions" => [
            "delete" => function($records) {
                foreach($records as $record) {
                    $record->delete();
                }
                return [
                "status" => "OK",
                "message" => "Successfully deleted the selected product types!",
                ];
            },
            ],
            "columns" => [
            "title" => "title",
            "users.username" => "users.username",
            "level" => "level",
            "users.username" => "users.username",
            "created_at" =>  function($value) {
                return $value->diffForHumans();
            }
            ],
            ]);
        return response()->json($responseData);
    }

Note the "users.username" => "users.username", last 8th line, How can i get the username from the users table ? 注意"users.username" => "users.username",最后八行,如何从users表中获取用户名?

The relationship names are mentioned above. 关系名称如上所述。

And it gives me the following error : 它给了我以下错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.username' in 'field list' (SQL: SELECT projects.*, categories.name AS b74HW, subcategory.name AS rLTng, users.username AS fUfHg from `projects` left join `categories` as `categories` on `categories`.`id` = `projects`.`categories_id` left join `sub_category` as `subcategory` on `subcategory`.`id` = `projects`.`subcategory_id` group by `id` order by `projects`.`id` desc limit 15 offset 0) 

The error is pretty straight. 错误很直接。 You are not using join on query so it's assuming you have a column called users.username and you have a column username in users table. 您没有在查询中使用联接,因此假设您有一个名为users.username的列,并且在users表中有一个列的用户名。

How are you calling the relation? 您如何称呼关系? Something like: 就像是:

$data = Users::find(1)->with('projects')->get(); //this user with id 1, and eager load the relation.

Also don't forget to loop trough the results like: 另外,不要忘记循环遍历以下结果:

foreach($data->projects as $project) { ... }

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

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