【问题标题】:Laravel get Messaging with ElouqentLaravel 使用 Eloquent 获取消息
【发布时间】:2020-03-20 14:30:22
【问题描述】:

我有三个表格和模型

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

您正在寻找的是 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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-29
    • 2013-09-05
    • 1970-01-01
    • 2014-07-18
    • 1970-01-01
    • 2020-11-06
    • 2020-11-25
    相关资源
    最近更新 更多