如何在雄辩的关系中建立关系Laravel

时间:2018-07-04 16:30:38

标签: php laravel

我有两个桌子

1-个项目

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-对话

-------------------------------------------
|id | project_id |  user_one | user_two   |
|1  |    1       |     5     |     3      |
|2  |    2       |     5     |     7      |
|3  |    3       |     5     |     10     |
-------------------------------------------

无论何时创建项目,都会使用该项目ID创建一个对话。现在,在Laravel中,我想使用口才关系来获取该项目的详细信息。

User_one是项目创建者,而user_two是我们分配给该产品的代理。

这是我尝试过的

class Chat extends Model {
 public function project()
    {
        return $this->belongsTo('App\ProjectModel');
    }
 }

class ProjectModel extends Model
{
   public $table = 'projects';
}

这是控制器功能

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();
}

所有这些之后,我得到一个错误-在null上调用成员函数project()

2 个答案:

答案 0 :(得分:2)

您可以尝试创建2个模型Conversationconversations(id, project_id, creator, agent)

public function conversations(){
    return $this->hasMany('App\Conversation');
} 

项目模型

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

会话模型

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);

     }

}

获取数据

$("#"+modal_field_prefix+"")

答案 1 :(得分:1)

您可以创建关系以及指定外键和所有者键,例如:

class Chat extends Model {
 public function project()
    {
        return $this->belongsTo(App\ProjectModel::class, 'project_id', 'id');
    }
 }

然后您将能够获得:

\App\Chat::where('id', $id)->first()->project;