我试图验证经过身份验证的用户是否喜欢帖子(或链接)。
我有一个like
模型user_id
,likeable_id
和likeable_type
(因为用户应该能够喜欢这两个单独模型的帖子或链接)
在App\User.php
:
public function likes() {
return $this->hasMany('App\Like');
}
public function likedCustom($str) {
$likedCustom = new Collection();
$this->likes()->where([
'likeable_type' => $str,
])->each(function ($like) use ($likedCustom) {
$likedCustom->push($like->likeable);
});
return is_null($likedCustom) ? false: $likedCustom;
}
public function likedEntries() {
$likedEntries = $this->likedCustom('post');
$links = $this->likedCustom('link');
$links->each(function ($link) use ($likedEntries) {
$likedEntries->push($link);
});
return is_null($likedEntries) ? false: $likedEntries;
}
由于我将App\Post
设置为'post'
而App\Link
设置为'link'
,因此效果非常好。在此之后,当我使用php artisan tinker
时,我能够将$entries
中的所有帖子和链接放在一个集合中。因此,App\User::find(1)->likedEntries()->contains(App\Post::find(1));
运行会返回true
。
问题从这里开始,因为我尝试在视图上实现此功能。例如,如果经过身份验证的用户喜欢帖子或链接:
@foreach ($entries as $entry)
@if ( Auth::user()->likedEntries()->contains($entry) )
<li class="active"> {{ $entry->title }} </li>
@else
<li> {{ $entry->title }} </li>
@endif
@endforeach
所以我猜测它可能是导致物体返回不同的原因。因为我在ViewComposers\EntryComposer.php
中以这种方式返回它们:
public function compose(View $view)
{
// $test = Post::all();
$entries = Post::all();
$links = Link::all();
$links->each(function ($link) use ($entries) {
$entries->push($link);
});
$entries = $entries->sortByDesc(function($entry) {
return $entry->score();
});
$view->with('entries', $entries);
// $view->with('entries', $test); // Didn't work either.
}
我错过了什么?
另外:
Psy Shell v0.8.12 (PHP 7.1.10 — cli) by Justin Hileman
>>> App\User::find(1)->likedEntries()
=> Illuminate\Support\Collection {#754
all: [
App\Post {#780
id: "1",
title: "debitis",
body: "Quis rerum amet saepe eligendi. Ullam ea consectetur rerum rem repellat qui qui vel. Aspernatur officiis aut tenetur est perspiciatis harum.",
user_id: "144",
category_id: "3",
created_at: "2017-10-23 12:38:34",
updated_at: "2017-10-23 12:38:34",
},
App\Link {#781
id: "1",
title: "Numquam consequuntur minima sunt aut vel facilis deleniti et.",
url: "https://www.dibbert.info/qui-voluptate-ratione-aperiam-et-ullam-perferendis-et",
user_id: "136",
category_id: "2",
created_at: "2017-10-23 12:38:36",
updated_at: "2017-10-23 12:38:36",
},
],
}
>>> App\User::find(1)->likedEntries()->contains(App\Post::find(1))
=> true
>>>
答案 0 :(得分:0)
在Polymorphic relations查看,它将简化很多关系逻辑以及用于从用户那里获取喜欢的对象的2个自定义函数。
任何方式,您需要在对查询执行->get()
后执行->where()
public function likedCustom($str) {
return $this->likes()->where('likeable_type', $str)->get()->map(function ($like) {
return $like->likeable;
});
// This will return a Collection that can be empty, so you
// should check against $collection->isEmpty() or ->count()
}