如何在雄辩的幼虫中使用条件关系

时间:2019-05-11 03:40:04

标签: laravel

我有一个“ conversation_message”表,并按“ sender_type”列(管理员/用户)分开了发送者角色。管理员和用户都在不同的表中。但是当我调用模型时,显示错误在null上调用成员函数addEagerConstraints()


表格列和数据

| id | id_group | id_reply | id_sender | sender_type | message 
| 1  | 1 | null | 3 | admin | Hi, I'm admin
| 2  | 1 | 1 | 3 | admin | I wanna give u promo
| 3  | 1 | 2 | 18 | user | What's promo ?

我已经尝试过使用列值作为条件,但是它不起作用。

Conversation_message.php

public function sender(){
        switch($this->sender_type){
            case "user":
                return $this->belongsTo(User::class, 'id_sender', 'id');
            case "admin":
                return $this->belongsTo(Admin::class, 'id_sender', 'id');
            default:
                return;           
        }
    }

InboxController.php

public function message_detail_chat($groupId){
        $data = [];
        $data['messages'] = Conversation_message::with('replies')
                        ->with('sender')
                        ->with('recipients')
                        ->where(['id_group' => $groupId])->get();
}

我希望按列值'sender_type'使用条件模型,但实际输出是错误的。

1 个答案:

答案 0 :(得分:0)

laravel提供查询范围,您可以从此处https://laravel.com/docs/5.8/eloquent#local-scopes

进行读取
#include <stdio.h>
int sum (int m, char n){
    return m+n;
}

int main(){
    char ch;
    int c;
    printf("Enter an integer and a character separated by a blank> ");
    scanf("%d %c",&c, &ch);
    if((c >= '0' && c <= '9')||(ch >= '0' && ch <= '9')){
        int cs = sum(c, ch - 0);
        printf("Character '%d' represents a digit. Sum of '%d' and '%c' is %d" , c, c, ch - 0, cs);
    }
    return 0;
}

现在您可以像这样访问发件人

   function userSender(){
      $this->belongsTo(User::class, 'id_sender', 'id');
      }

     function adminSender(){

       return $this->belongsTo(Admin::class, 'id_sender', 'id');

     }

public function scopeSender($query)
{
    return $query
          ->when($this->sender_type === 'user',function($q){
              return $q->with('userSender');
         })
         ->when($this->sender_type === 'admin',function($q){
              return $q->with('adminSender');
         }); 

}

这应该给您正确的发件人。希望能帮助到你。