繁体   English   中英

Laravel DB查询需要帮助

[英]Laravel DB queries help needed

我是Laravel的新手,难以理解查询内容

我有2张桌子

  1. 用户[id,email,fname,lname]

  2. 潜在客户[id,其他一些字段,客户,代理]

客户端和代理是用户表ID的外键。

使用下面的代码,我可以从Leads表中检索数据,但是在那里我获得client = 3 agent = 4这样的东西

但我不想显示这些ID,而是希望从用户表中获得这些ID的名称

怎么做?

到目前为止,我在控制器中具有此功能

/**
 * @return \Illuminate\Http\Response
 */
public function leads(){

    if(Auth::user()->role == 'admin'){

        $leads = Leads::all();

        // here in the $leads i get datas like ['id' => 1, 'field1' => 'test', 'field2'=> 'test2', 'client_id'=> 2, 'agent_id'=> 3] , but i want to get the names of the client and agent from the user table which we can do in normal sql query by joining but how to do with laravel?

    }

    return view('leads', compact('leads'));
}

怎么做?

在“用户模型和潜在顾客”模型中,我只有默认代码,而我有代码

如果能得到一些快速的帮助将不胜感激

首先,您需要将列名更改为agent_idclient_id而不是agentclient 否则,您需要相应地更新以下代码。

从您的答案来看,我认为您需要在Leads模型中执行以下操作:

定义代理商与客户的关系

public function agent()
{
    return $this->belongsTo(User::class, 'agent_id');
}

public function client()
{
    return $this->belongsTo(User::class, 'client_id');
}

在对Leads模型的每次查询调用中自动加载它们。

protected $with = ['agent', 'client'];

完成上述步骤后,您只需编写以下信息即可列出潜在客户的代理商/客户:

$lead->agent->name;
$lead->client->name;

暂无
暂无

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

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