代码之家  ›  专栏  ›  技术社区  ›  Lluís Puig Ferrer

有数组时如何进行查询

  •  2
  • Lluís Puig Ferrer  · 技术社区  · 7 年前

    我有三个表:client、project和client\u project。

    我想在视图中显示一个客户的所有项目。

    下面是解释代码:

    <?php
    
    public function editClient($id)
    {
        $client = Client::find($id);
    
        // I get an array with client_id and project_id of the clients 
        // which is the same I pass in the URL.
        $client_project = DB::table('client_project')->where('client_id',$id)->get();
    
        // return view('cms.public.views.clients.editclient')->withClient($client);
    }
    

    现在,我想显示当表项目的字段id在$client\u项目数组中具有相同的project\u id值时的项目名称。

    下面是一个例子,如果它只是一个值,可能会有所帮助。

    public function editClient($id) 
    {
        $client = Client::find($id);
        $client_project = DB::table('client_project')->where('client_id',$id)->first()->project_id;
        $project = DB::table('projects')->where('id',$client_project)->first();
    
        return $project;
    }
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Mahfuz Shishir    7 年前

    使用一对多关系。

    在客户端。php模型

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

    在你的项目中。php模型

    public function client()
    {
       return $this->hasMany('App\Client', 'client_id');
    }
    

    现在打电话

    $client_project = Client::find($id)->projects;
    

    https://laravel.com/docs/5.5/eloquent-relationships#one-to-many

        2
  •  0
  •   Mavin    7 年前

    而不是采取 first() 客户项目,全部使用 whereIn() 项目选择中的方法。

    $projects = DB::table('projects')->whereIn('id', function ($query) {
            $query->select('project_id')->from('client_project')->where('client_id', $id);
    })->get();
    

    以下是laravel文档链接: Laravel 5.5 Documentation - Queries#where-clauses

    我是在回答我对你的要求的理解,这不是很清楚。