我制作了一个网页,我的用户可以在其中创建两种类型的内容:'活动'和'活动集合'。我想检查当前用户是否已经在他的任何收藏中使用了一个活动。
这两种内容之间的关系是belongsToMany
。每个Activity都可以在一些Collection中使用,每个Collection都有很多活动......所以有一个数据透视表来处理它。
我得到了Activity ID
User ID
,但我不知道该怎么做。
任何想法?非常感谢!!
修改
我的控制器:
$actividads = Actividad::orderBy('created_at', 'DESC')->paginate(10);
$id_user = Sentry::getUser()->id;
$fichas = Ficha::where('user_id', $id_user)->orderBy('created_at', 'DESC')->get();
$user = User::find($id_user);
$actividadEnFicha = Actividad::has('fichas')
->get();
我的观点:
@foreach($actividads as $actividad)
@foreach($actividadEnFicha as $a)
@if($actividad->id == $a->id)
{{ $a->id }}
@endif
@endforeach
@endforeach
我想显示ficha
的名称,而不是$a->id
(id actividad)......但我还不知道如何获得它。
答案 0 :(得分:0)
假设关系activities
(User hasMany Activity
):
$user = User::find($userId);
// returns Activity only if it belongs to one or more collections, null otherwise
$activityInCollection = $user->activities()
->has('collections')
// with('collections') to eager load collections
->find($activityId);
// returns Activity with given id only if it does not belong to any collection
$activitiyWithoutCollections = $user->activities()
->has('collections', '=', 0);
// all activities of the user, that belong to one or more collections
$activitiesInCollections = $user->activities()
->has('collections')
// with('collections') to eager load collections
->get();
// all activities of the user, that belong to exactly 3 collections
$activitiesInCollections = $user->activities()
->has('collections', '=', 3)
// with('collections') to eager load collections
->get();
依旧......