【问题标题】:Laravel elequent model/RelationshipLaravel 雄辩的模型/关系
【发布时间】:2021-03-25 18:45:46
【问题描述】:

假设我们有带有列的对话模型

  • 身份证
  • user_id
  • user2_id
  • updated_at

用户模型

  • 身份证
  • 姓名

如您所见,对话有两个参与者 ID,即 user_id 和 user2_id 其中一个参与者必须是当前用户,

所以,我想列出以其他参与者姓名作为对话名称的对话

我该如何实现这个??

【问题讨论】:

  • 为什么要实现随机插入?这没有意义
  • 我尝试做的是创建一个有两个参与者的对话表,在每个对话中,其中一个参与者必须是当前用户,我想将与另一个参与者的对话列为对话名称

标签: laravel


【解决方案1】:

我得到了答案,我只需要用不同的函数名建立两个关系

class conversation extends Model
{
   use HasFactory;
   protected $fillable=['user_id','user2_id'];
   public function user1()
    {
      return $this->belongsTo(User::Class, 'user_id');
    }
    public function user2()
    {
      return $this->belongsTo(User::Class, 'user2_id');
    }
}

所以当我检索时,我需要在 控制器.php

public function getConvs()
{
    $user_id = Auth::user()->id;
    return conversation::where([
        ['user_id', $user_id],
    ])->orwhere([
        ['user2_id', $user_id],
    ])->with('user2')->with('user1')->get();
}

在 example.vue 文件中

export default 
{    
    data(){
        return{
     
        convs_id: [],
        convs: [],
        }
    },
   
    created(){
       
        this.fetchConversation();
        t
    },
    methods:
    {
        
        fetchConversation()
        {
            axios.get('getConvs').then(response=>{
                this.convs = response.data;
                
            });
            
        }
    }
}

所以在视图中我们可以像这样简单地使用

<li v-for="(conv, index) in convs" :key="index" class="pb-1">
                    
                       <div class="bg-yellow-100 p-2 m-2 rounded-lg" v-if="conv.user1.name == user.name"> <h1>{{conv.user2.name}}</h1></div>
                       <div class="bg-yellow-100 p-2 m-2 rounded-lg" v-else > <h1>{{conv.user2.name}}</h1></div>
            
                    </li> 

【讨论】:

    猜你喜欢
    • 2019-02-12
    • 2013-06-04
    • 2016-11-26
    • 2018-02-19
    • 2019-07-16
    • 1970-01-01
    • 2019-06-27
    • 2014-08-03
    相关资源
    最近更新 更多