简体   繁体   English

Laravel DB查询需要帮助

[英]Laravel DB queries help needed

I am new in Laravel, Having some difficulties to understand the queries 我是Laravel的新手,难以理解查询内容

I have 2 tables 我有2张桌子

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

  2. Leads [id, other some fields, client, agent] 潜在客户[id,其他一些字段,客户,代理]

the client and agent is the foreign key of users table's id.. 客户端和代理是用户表ID的外键。

with the below code i can retrive datas from the Leads table but there i get client = 3 agent = 4 something like this 使用下面的代码,我可以从Leads表中检索数据,但是在那里我获得client = 3 agent = 4这样的东西

but instead of showing those ids i want to get the names of those ids from the user table 但我不想显示这些ID,而是希望从用户表中获得这些ID的名称

how to do it? 怎么做?

In the controller i have this function as of now 到目前为止,我在控制器中具有此功能

/**
 * @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'));
}

How it can be done ? 怎么做?

in the Users Model & Leads model i have only the default codes i have the code 在“用户模型和潜在顾客”模型中,我只有默认代码,而我有代码

will appreciate if get some quick help 如果能得到一些快速的帮助将不胜感激

First you need to change your column names to agent_id & client_id instead of agent & client . 首先,您需要将列名更改为agent_idclient_id而不是agentclient Otherwise you need to update the following code accordingly. 否则,您需要相应地更新以下代码。

Judging by your answer, i think you need to do something like this in Leads model: 从您的答案来看,我认为您需要在Leads模型中执行以下操作:

Define relations for agent & client 定义代理商与客户的关系

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

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

Autoload them on every query call to Leads model. 在对Leads模型的每次查询调用中自动加载它们。

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

After you do the above steps, you can simply list an agent/client for a lead by writing: 完成上述步骤后,您只需编写以下信息即可列出潜在客户的代理商/客户:

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

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

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