[英]Laravel DB queries help needed
我是Laravel的新手,難以理解查詢內容
我有2張桌子
用戶[id,email,fname,lname]
潛在客戶[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_id
和client_id
而不是agent
& client
。 否則,您需要相應地更新以下代碼。
從您的答案來看,我認為您需要在Leads
模型中執行以下操作:
public function agent()
{
return $this->belongsTo(User::class, 'agent_id');
}
public function client()
{
return $this->belongsTo(User::class, 'client_id');
}
protected $with = ['agent', 'client'];
完成上述步驟后,您只需編寫以下信息即可列出潛在客戶的代理商/客戶:
$lead->agent->name;
$lead->client->name;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.