Laravel 5 使用 where 子句连接表查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35447274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:14:58  来源:igfitidea点击:

Laravel 5 Join table query with where clause

phpformslaravel

提问by Ajaxcbcb

Trying to achieve with Laravel 5.2's eloquent model

尝试用 Laravel 5.2 的 eloquent 模型实现

I have 2 tables:

我有2张桌子:

1) projects (id, projectName, users_id)

1) 项目(id、projectName、users_id)

2) todo (id, todoName, ProjectID[id], users_id)

2) todo (id, todoName, ProjectID[id], users_id)

i want to join these table and foreach the table content with

我想加入这些表格并使用 foreach 表格内容

->where('users_id','=',Auth()->User()->id)

Part of the code

部分代码

$todos = DB::table('to_dos')->join('projects','to_dos.projectID','=','projects.projectName')
                                                            ->where('users_id','=',Auth()->User()->id)
                                                            ->get();

the objective is to print toDoName and projectName

目标是打印 toDoName 和 projectName

@foreach($todos as $todo)
    {{$todo -> ToDoName}}
    {{$todo -> projectName}}
    <br>
@endforeach

回答by Jilson Thomas

The best way is to create a relation between the tables and eager load the relation.

最好的方法是在表之间创建关系并预先加载关系。

In your Todomodel, add the following method:

在您的Todo模型中,添加以下方法:

public function project()
{
  return $this->belongsTo('App\Project');
}

Now, from your controller, you can just call:

现在,从您的控制器,您可以调用:

$todos = Todo::with('project')->where('user_id', Auth::id());

This would give you the Todos for the currently logged in user with the corresponding projects.

这将为您提供当前登录用户的 Todos 以及相应的项目。

Now in your view, you can use:

现在在您看来,您可以使用:

@foreach($todos as $todo)
   {{ $todo->name }}
   {{ $todo->project->name }}
@endforeach

Note:It will be good if you follow some conventions. The table columns shall be as follows:

注意:如果你遵循一些约定会很好。表格列如下:

userstable -> Model: User.php
columns: id, name....

users表 -> 模型:User.php
列:id, name....

projectstable -> Model: Project.php
columns: id, name, user_id

projects表- >型号:Project.php
列:idnameuser_id

todostable-> Model: Todo.php
columns: id, name, project_id, user_id.

todos表-> 模型:Todo.php
列:id, name, project_id, user_id

Remember, when you follow the convention over configurations, things are much easier.

请记住,当您遵循约定而不是配置时,事情会容易得多。

回答by Jobin Jose

Try this,

尝试这个,

$todos = DB::table('to_dos as T')
->leftjoin('projects as P','T.projectID','=','P.projectName')
->Where('T.users_id',Auth()->User()->id)
->get();