检索另一个表中不存在的数据

时间:2016-12-02 16:54:43

标签: laravel-5

我有两张表SCHOLAR和MEMBER表。我想显示来自学者表的学者名单,其中scholar_id没有在会员表中找到。但是我的第二个dd的结果是空的,实际上它在数据库中有数据。我做错了什么?我认为我的代码很好。

public function list()
{
    $scholars = Member::all();
    $scholar_ids = [];
    foreach ($scholars as $scholar) {
    array_push($scholar_ids, $scholar->scholar_id);
}

$scholar_exits = Scholar::where('scholar_id','=', $scholar_ids)->get();

<!-- First -->
dd($scholar_ids);
<!-- Second -->
dd($scholar_exits);

}

<!-- First dd result -->
array:7 [▼
  0 => 7
  1 => 8
  2 => 12
  3 => 13
  4 => 14
  5 => 15
  6 => 16
]

<!-- Second dd result -->

Collection {#275 ▼
  #items: []
}

希望有人能在这里帮助我。

2 个答案:

答案 0 :(得分:0)

怎么样?
public function list()
{
    $members = Member::all();
    $members = $members->toArray();
    $scholar_ids = array_pluck($members, 'scholar_id');
}

//Are you sure you do not want to refer to 'id' instead of 'scholar_id'?
$scholar_exits = Scholar::whereIn('scholar_id', $scholar_ids)->get();

}

答案 1 :(得分:0)

public function list()
{
    $scholars = Member::get(['scholar_id'])->toArray();

    if(!is_null($scholars)) $scholars = array_flatten($scholars);
    else $scholars = [];

    $scholar_exits = Scholar::whereNotIn('scholar_id', $scholars)
                     ->get();
}