【问题标题】:Pass Parameter to Relationship Function or alternative solution将参数传递给关系函数或替代解决方案
【发布时间】:2020-02-20 06:13:24
【问题描述】:

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

我有一个名为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"

所以我可以在我的控制器中检查用户是否喜欢来自 DB 的帖子并将其发送到查看...但是有很多 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>

但这当然行不通....那么我的选择是什么?我应该在控制器 fopr 中检查这个更新我的模板的每个调用吗?

【问题讨论】:

    标签: php laravel eloquent orm laravel-5.8


    【解决方案1】:
    # ChannelPost
    public function isLikedBy($user_id): bool
    {
        return $this->PostLike->reduce(function ($carry, $item) use ($user_id) {
            return $carry || $item->user_id == $user_id;
        }, false);
    }
    
    <i class="like-icon {{ $post->isLikedBy(auth()->id()) ? 'liked' : '' }}"></i>
    

    【讨论】:

    • thanx 但它总是返回 true ...我已将 }, true); 更改为 }, false); 并且它有效
    • 啊,是的,这应该可以解决问题。我会编辑它。如果返回的是$carry &amp;&amp; ...,我通常会输入}, true);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-08
    • 1970-01-01
    • 2011-07-20
    • 1970-01-01
    • 2012-09-02
    • 2012-08-11
    • 1970-01-01
    相关资源
    最近更新 更多