【问题标题】:Laravel 4 - Check if a user has used some contentLaravel 4 - 检查用户是否使用了某些内容
【发布时间】:2014-07-25 15:46:41
【问题描述】:

我正在制作一个网页,我的用户可以在其中创建两种类型的内容:“活动”和“活动集合”。我想检查当前用户是否已经在他的任何收藏中使用了一个活动。

这两种内容的关系是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)...但我仍然不知道如何获取它。

【问题讨论】:

    标签: laravel-4 eloquent relationship pivot-table


    【解决方案1】:

    假设关系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();
    

    等等……

    【讨论】:

    • 非常感谢!!有用!!但我的观点仍然存在问题。我想在我的视图中显示我已经使用过的每个集合的名称(我称之为“ficha”)。我用我的代码编辑问题...
    • fichas 将是Eloquent\Collection,因此您需要$a->fichas->first()->name 或遍历这些fichas。我建议立即加载它们,就像在编辑中一样。
    • 如果我想获取所有 fichas 名称的列表,而不仅仅是 first()??
    • @foreach ($actividad->fichas as $ficha) <li>{{ $ficha->name }}</li> 例如
    • uopssss 简单!!谢谢;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多