[英]How to Create Relation in Eloquent Relationships Laravel
I have Two Table 我有两张桌子
1- projects 1-项目
User with id 5 has created 3 project - which means he will have 3 unique conversation with our different agent ID为5的用户创建了3个项目-这意味着他将与我们的其他业务代表进行3次独特的对话
----------------------------------------
|id | user_id | title | time |
|1 | 5 | Example | 2018-06-30 |
|2 | 5 | Example | 2018-06-30 |
|3 | 5 | Example | 2018-06-30 |
----------------------------------------
2- conversation 2-对话
-------------------------------------------
|id | project_id | user_one | user_two |
|1 | 1 | 5 | 3 |
|2 | 2 | 5 | 7 |
|3 | 3 | 5 | 10 |
-------------------------------------------
Whenever a project is created, a conversation is created with that project id, Now in Laravel i want to get that project detail using Eloquent Relationships. 每当创建一个项目时,都会使用该项目ID创建一个对话。现在在Laravel中,我想使用雄辩的关系来获取该项目的详细信息。
User_one is the project creator and user_two is our agent assigned to that product. User_one是项目创建者,而user_two是我们分配给该产品的代理。
This is What I've tried 这就是我尝试过的
class Chat extends Model {
public function project()
{
return $this->belongsTo('App\ProjectModel');
}
}
class ProjectModel extends Model
{
public $table = 'projects';
}
Here is the controller function 这是控制器功能
public function Progress($id){ // Id passed here is 2, so it should show detail of project number 2
return \App\Chat::find($id)->project()->get();
}
After all this I'm getting an error - Call to a member function project() on null 毕竟,我得到一个错误-在null上调用成员函数project()
You can try like this with creating 2 Models Project
and Conversation
您可以尝试通过创建2个Models
Project
和Conversation
进行尝试
table 表
conversations(id, project_id, creator, agent)
Project Model 项目模型
public function conversations(){
return $this->hasMany('App\Conversation');
}
Conversation Model 会话模型
public function project(){
return $this->belongsTo('App\Project', 'project_id');
}
public function creatorUser(){
return $this->belongsTo('App\User', 'creator');
}
public function agentUser(){
return $this->belongsTo('App\User', 'agent');
}
Fetch Data 获取数据
public function Progress($id){ // Id passed here is 2, so it should show detail of project number 2
$chats = Conversation::with('project', 'creatorUser', 'agentUser')->where('project_id', 2)->get();
foreach($chats as $chat){
dd($chat->project); //it will always print same project because we have filter the conversation by project_id
dd($chat->creatorUser);
dd($chat->agentUser);
}
}
you can create a relation Along with specifying foreign Key and owner key like: 您可以创建关系以及指定外键和所有者键,例如:
class Chat extends Model {
public function project()
{
return $this->belongsTo(App\ProjectModel::class, 'project_id', 'id');
}
}
and then you will be able to get: 然后您将能够获得:
\App\Chat::where('id', $id)->first()->project;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.