//样本数据库

起初学者有1,2,3,4,5,6个ID

Scholar
Id
1
2
3
4
5
6


现在将1和2放在表Member下

Member
Id
1 - taken
2 - taken


接下来的3和4在表AddRequest下

AddRequest
Id
3 - taken
4 - taken


现在Scholar表应该只包含我要显示的ID 5和6。

我如何使用下面的代码解决此问题

public function ListOrgaScholar($ship_id)
{
    $members = Member::where('ship_id','=',$ship_id)->get();
    $members = $members->toArray();
    $scholar_ids = array_pluck($members, 'scholar_id');
    $scholar_exits = Scholar::whereNotIn('scholar_id', $scholar_ids)->get();

    $requests = AddRequest::where('ship_id','=',$ship_id)->get();
    $requests = $requests->toArray();
    $scholar_ids = array_pluck($requests, 'scholar_id');
    $add_exits = Scholar::whereNotIn('scholar_id', $scholar_ids)->get();

    if ($scholar_exits == true && $add_exits == true) {

    $scholars = (new Scholar)->newQuery()->select('*');

    $scholars = $scholars->get();
    dd($scholars);
}else{
}
}


dd的结果

Collection {#302 ▼
  #items: array:7 [▼
    0 => Scholar {#305 ▶}
    1 => Scholar {#306 ▶}
    2 => Scholar {#307 ▶}
    3 => Scholar {#308 ▶}
    4 => Scholar {#309 ▶}
    5 => Scholar {#310 ▶}
    6 => Scholar {#311 ▶}
  ]
}


This for Member and AddRequest Table

This for Scholar

最佳答案

在对成员和addRequests进行所有检查之后,您试图从Scholar表中选择所有内容,这就是您获得所有六个记录的原因。

我将在is-member表中添加两个字段,如has-requestscholar,并根据-is-member becomes true when the Scholar transitions to become a memberhas-request becomes true when the Scholar add a request之类的事件将布尔值更新为true。因此,获得既不是会员也不提出任何要求的学者变得非常容易。

但是,根据您的情况,我认为您应该尝试以下操作:

public function ListOrgaScholar($ship_id)
{
    $scholar_ids = [];
    $members = Member::where('ship_id','=',$ship_id)->get();
    //$members = $members->toArray();
    //$scholar_ids = array_pluck($members, 'scholar_id');
    //$scholar_exits = Scholar::whereNotIn('scholar_id', $scholar_ids)->get();
    foreach($members as $member){
        $scholar_ids[] = $member->scholar_id;
    }

    $requests = AddRequest::where('ship_id','=',$ship_id)->get();
    //$requests = $requests->toArray();
    //$request_scholar_ids = array_pluck($requests, 'scholar_id');
    //$add_exits = Scholar::whereNotIn('scholar_id', $scholar_ids)->get();
    foreach($requests as $request){
        $scholar_ids[] = $request->scholar_id;
    }

    $scholars = Scholar::whereNoIn('scholar_id', $scholar_ids)->get();
    dd($scholars);
}

关于php - 从一个表访问不属于其他两个表的数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40974644/

10-11 03:12