简体   繁体   中英

Laravel 5.3 : Many to many realtionship's data

I have ,many to many relationship between User and Project

Realtionship Names are : User model have projects and Project model have 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 ?

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.

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) { ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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