duankuai6991 2018-07-04 16:30
浏览 32
已采纳

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

I have Two Table

1- projects

User with id 5 has created 3 project - which means he will have 3 unique conversation with our different agent

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

-------------------------------------------
|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.

User_one is the project creator and user_two is our agent assigned to that product.

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

  • 写回答

2条回答 默认 最新

  • doumi1311 2018-07-04 16:40
    关注

    You can try like this with creating 2 Models Project and 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);
    
         }
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度