如何在laravel morph关系中通过id获取不可移植类型的记录

时间:2019-05-03 08:33:53

标签: laravel laravel-5 eloquent laravel-5.8

对于消息系统,我已经使用四个表设置了两个变形关系。

我的问题是?

  1. 如何从接收收藏的特定学生的消息中得到信息?

例如,如果 X和Y学生 A员工

发送邮件

当我查询A员工收到的消息时,例如:

$staff = \App\Staff::find(1);
$all_message_recieves = $staff->receives;

我从学生X和Y 收到了两条消息,但我只想要学生X 的消息

表结构是

tbl_message

id messageable_id, messageable_type, subject, message

1     1              app\staff        msg1     msg1
2     2              app\staff        msg1     msg1
3     1              app\student      msg2     msg2
4     2              app\student      msg2     msg2
tbl_message_receiver

id, message_id , receiveable_id, receiveable_type

1     1            1                 app\student
2     2            2                 app\student
3     3            1                 app\staff
3     4            1                 app\staff
Staff

id name
1   A
2   B
Student

id name
1   X
2   Y

Message.php模型

class Message extends Model
{

    public $table = "tbl_message";

    public function messageable()
    {
        return $this->morphTo();
    }
}

Messagereceive.php模型

class Messagereceive extends Model
{
    public $table = "tbl_message_receiver";
    public function receiveable()
    {
        return $this->morphTo();
    }

    public function message()
    {
         return $this->hasOne('App\Message');
    }
}

Staff.php模型

class Staff extends Model
{

    public function messages()
    {
        return $this->morphMany('App\Message', 'messageable');
    }

    public function receives()
    {
        return $this->morphMany('App\Messagereceive', 'receiveable');
    }
}

Student.php模型

class Student extends Model
{

    public function messages()
    {
        return $this->morphMany('App\Message', 'messageable');
    }


    public function receives()
    {
        return $this->morphMany('App\Messagereceive', 'receiveable');
    }
}

0 个答案:

没有答案