我得到了答案,我只需要用不同的函数名建立两个关系
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>