将参数传递给关系函数或替代解决方案

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

我知道已经问过这个问题,但答案对我不起作用

我有一个名为channel_posts的表,带有此模型

class ChannelPost extends Model
{

    function PostLike( ){
        return $this->hasMany('App\ChannelPostLike' ,'post_id');
    }

}

[还有channel_post_likes表,我存储喜欢的内容

channel_post_likes : id , post_id , user_id

现在在我的模板中有一个图标..如果用户喜欢该帖子,我希望它具有class="liked"

因此我可以在控制器中检查用户是否喜欢数据库中的帖子并将其发送给查看...但是有很多ajax调用可以部分更新模板...例如,如果用户发送了针对该帖子的评论,通过ajax响应发布即时消息更新模板

    function comment_store(Request $request , $id ){

         //store in db

        echo json_encode(['html'=> view('include.channel-post-comment' , compact('comments' ,'post'))->render()]);
    }

这意味着我必须检查用户ahs是否也已经喜欢这里的帖子并将其注入以查看

我想知道是否可以在模板中执行此操作

就像我可以将此关系添加到ChannelPost模型中

    function UserPostLike( $user_id ){
    return $this->hasOne('App\ChannelPostLike' ,'post_id')->where('user_id' , $user_id) ;
}

并且在模板中我可以拥有

<i class="like-icon @if($post->UserPostLike(Auth::user()->id)) liked @endif "></i>

但是当然这是行不通的。我是否应该在控制器中检查每次更新模板的调用?

php laravel eloquent orm laravel-5.8
1个回答
0
投票
# ChannelPost
public function isLikedBy($user_id): bool
{
    return $this->PostLike->reduce(function ($carry, $item) use ($user_id) {
        return $carry || $item->user_id == $user_id;
    }, true);
}
<i class="like-icon {{ $post->isLikedBy(auth()->id()) ? 'liked' : '' }}"></i>
© www.soinside.com 2019 - 2024. All rights reserved.