将参数传递给关系函数或替代解决方案
Pass Parameter to Relationship Function or alternative solution
我知道有人问过这个问题,但答案对我不起作用
我有一个叫 channel_posts
的 table 和这个型号
class ChannelPost extends Model
{
function PostLike( ){
return $this->hasMany('App\ChannelPostLike' ,'post_id');
}
}
并且有channel_post_likes
table 我存储了喜欢
channel_post_likes : id , post_id , user_id
现在在我的模板中有类似的图标.. 如果用户喜欢 post 我希望它有 class="liked"
所以我可以在我的控制器中检查用户是否喜欢数据库中的 post 并将其发送到视图...但是有很多 ajax 调用会部分更新模板.. . 例如,如果用户通过 ajax 响应
发送对 post 即时消息更新模板的评论
function comment_store(Request $request , $id ){
//store in db
echo json_encode(['html'=> view('include.channel-post-comment' , compact('comments' ,'post'))->render()]);
}
这意味着我必须检查用户是否已经喜欢这里的 post 并将其注入以查看
我想知道我是否可以在模板中做到这一点
就像我可以将此关系添加到 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 中检查这个吗?
# 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>
我知道有人问过这个问题,但答案对我不起作用
我有一个叫 channel_posts
的 table 和这个型号
class ChannelPost extends Model
{
function PostLike( ){
return $this->hasMany('App\ChannelPostLike' ,'post_id');
}
}
并且有channel_post_likes
table 我存储了喜欢
channel_post_likes : id , post_id , user_id
现在在我的模板中有类似的图标.. 如果用户喜欢 post 我希望它有 class="liked"
所以我可以在我的控制器中检查用户是否喜欢数据库中的 post 并将其发送到视图...但是有很多 ajax 调用会部分更新模板.. . 例如,如果用户通过 ajax 响应
发送对 post 即时消息更新模板的评论 function comment_store(Request $request , $id ){
//store in db
echo json_encode(['html'=> view('include.channel-post-comment' , compact('comments' ,'post'))->render()]);
}
这意味着我必须检查用户是否已经喜欢这里的 post 并将其注入以查看
我想知道我是否可以在模板中做到这一点
就像我可以将此关系添加到 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 中检查这个吗?
# 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>