简体   繁体   English

如何传递多个到多个关系来查看数组[Laravel 5]

[英]How to pass many to many relations to view as array[Laravel 5]

I try to pass array to view for my relations.... I have users and projects table in realation.... 我尝试传递数组来查看我的关系....我有用户和项目表在realation ....

Here is User Model: 这是用户模型:

public function projects(){
    return $this ->belongsToMany('App\Project','project_user');
}


public function getUserList(){
    return $this -> projects;
}

Here is my home controller: 这是我的家庭控制器:

public function project(User $project){
            $this -> selected = $project;
            return view('projects',array('selected' =>$project -> selected -> getUserList()->lists('id') ));
        }

NOTE 注意

If I change my home controller, this line: 如果我改变我的家庭控制器,这一行:

return view('projects',array('selected' => $project -> selected -> getUserList()->lists('id') ));

into this: 进入这个:

return view('projects',array('selected' => Auth::user -> getUserList()->lists('id') ));

it works fine... 它工作得很好......

Anyone know why It now work with method injection? 任何人都知道为什么现在可以使用方法注入?

Short answer: Laravel doesn't know what to do when you type-hint your User model. 简短回答:当您键入提示您的用户模型时,Laravel不知道该怎么做。

Longer answer: Since the current logged in user's information is stored in the Authentication portion of Laravel's code, one option is to type-hint the Illuminate\\Contracts\\Auth\\Guard interface ( API docs ) in your method descriptor to get an instance of it. 更长的答案:由于当前登录的用户信息存储在Laravel代码的Authentication部分中,因此一种方法是在方法描述符中键入提示Illuminate\\Contracts\\Auth\\Guard接口( API文档 )以获取它的实例。

You can then use the user property to access an instance of the User model reflecting the currently logged in user. 然后,您可以使用user属性访问反映当前登录用户的User模型实例。 This code is essentially what you already have here: Auth::user -> getUserList()->lists('id') . 这段代码基本上就是你已经拥有的代码: Auth::user -> getUserList()->lists('id')

The benefit to using the Guard interface inside of Illuminate\\Contracts is that if a package or service provider redefines the concrete implementation of the Guard interface (the reason to do this would be swapping out how authentication works in your application), your code will not require changes due to it being bound to the contract defined by that interface, rather than using the Auth facade which may no longer function in the same manner. 使用的好处Guard的内部接口Illuminate\\Contracts是,如果一个包或服务供应商重新定义了具体实现的Guard接口(这样做的原因将被换掉的认证您的应用程序是如何工作的),你的代码不会需要更改,因为它绑定到该接口定义的合同,而不是使用可能不再以相同方式运行的Auth Facade。

Hope this helps! 希望这可以帮助! Feel free to ask questions :) 随意问的问题 :)

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

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