2016-12-02 49 views
0

我有两个表SCHOLAR和MEMBER表。我想显示Scholar表中没有scholar_id在Member表中找到的学者名单。但是我的第二个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: [] 
} 

希望任何人都可以帮助我。

+0

1)我可能会建议你使用'array_pluck'代替或'foreach'和'array_push'。 2)我猜'学者:: whereIn('id',$ scholar_ids) - > get();'应该这样做。 – Wistar

回答

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(); 

} 
+0

是的先生我使用scholar_id而不是id。但先生谢谢你分享你的聪明才智。现在它的工作 – Gatzmar

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(); 
} 
相关问题