Laravel使用Elouqent进行消息传递

问题描述 投票:0回答:1

我有三个表和模型

  1. 个人资料
  2. 消息
  3. 用户

我有三种型号1.个人资料2.留言3.用户

profile table:    id|user_id|profile_image
messages table:  id|message|user_id|friend_id
user table  : id|name|etc

我只收到消息,但我想获得带有个人资料和用户名的消息。

   $chat=Message::where(function ($query) use($id){
       $query->where('user_id',Auth::user()->id)->where('friend_id',$id);
    })->orWhere(function ($query) use($id){
        $query->where('user_id',$id)->where('friend_id',Auth::user()->id);
    })->get(); 
laravel message relational
1个回答
1
投票
您正在寻找的是relationships找到了here

您必须在拥有其他模型数量的模型中定义关系,反之亦然。

在您提出问题后,您的模型可能应采用以下结构:

<?php class Profile extends Model { // a profile belongs to an user function user() { return $this->belongsTo('App\Model\User', 'user_id'); } }

然后,在您的User模型中。

<?php class User extends Model { // an user has many profiles function profiles() { return $this->hasMany('App\Model\Profile', 'id'); } // an user has many messages function messages() { return $this->hasMany('App\Model\Message', 'id'); } }

最后,在您的Message模型中。

<?php class Message extends Model { // a message belongs to an user function user() { return $this->belongsTo('App\Model\User', 'user_id'); } // a message was sent to one friend function friend() { return $this->hasOne('App\Model\Friend', 'friend_id'); } }

这就是在Laravel中建立关系的方式,您可以根据所使用的Laravel版本找到文档here

最后,您可以像这样使用Eloquent。

Profile::with('user)->get(); Message::with('user')->get(); $message = Message::find(1)->user()->where('etc', 'etc')->first();

© www.soinside.com 2019 - 2024. All rights reserved.