Laravel检查集合是否包含外键

时间:2022-10-15 23:16:46

I was wondering if there is a function or something else, where you can get an other element from a collection than the primary key... For example if votes would have a foreign key 'user_id', how do I check this? On the laravel doc there was only an example to check the primary key by using contains(). Can anyone help me out?

我想知道是否有一个函数或其他东西,你可以从集合中获得一个元素而不是主键...例如,如果投票有一个外键'user_id',我该如何检查?在laravel doc上,只有一个示例通过使用contains()来检查主键。谁能帮我吗?

Example that checks if there is a vote with id = 2

检查是否存在id = 2的投票的示例

@foreach($projects as $project)
  @if ($project->votes->contains(2))
  //
  @endif
@endforeach

I would want something to check if there is a vote that has a 'user_id' = signed in users id

我想要检查是否有一个'user_id'=签名用户ID的投票

@foreach($projects as $project)
  @if ($project->votes->contains('user_id' == Auth::id()))
  //
  @endif
@endforeach

2 个解决方案

#1


13  

if ($votes->contains('user_id', auth()->id())) {
    //
}

#2


1  

In your model

在你的模型中

public static checkForeign($thisId) {
    ( $thisId == Auth::user()->id ) ? return true : return false;
}

In the view

在视图中

@if ( ModelName::checkForeign($project->votes->id) ) 
    // Do something
@endif

#1


13  

if ($votes->contains('user_id', auth()->id())) {
    //
}

#2


1  

In your model

在你的模型中

public static checkForeign($thisId) {
    ( $thisId == Auth::user()->id ) ? return true : return false;
}

In the view

在视图中

@if ( ModelName::checkForeign($project->votes->id) ) 
    // Do something
@endif