dou7851 2014-12-04 09:37
浏览 108

从表A中选择所有ID,其中id不在数据透视表中

I have a category table and a pivot table which determines the child categories. I wanted to use eloquent to select all the top level categories (categories that do not have a parent). I did want to do it with one eloquent query but haven't managed to get my head around it.

Database Structure

library_categories
    id
    title
    slug

library_category_relationships
    id
    parent_id
    category_id

Model

class LibraryCategory extends \Eloquent {

    public function children()
    {
        return $this->belongsToMany('LibraryCategory', 'library_category_relationships', 'parent_id', 'category_id');
    }

    public function parents()
    {
        return $this->belongsToMany('LibraryCategory', 'library_category_relationships', 'category_id', 'parent_id');
    }

}

Current Query (Located in a repository method)

$relationshipIds = DB::table('library_category_relationships')
                            ->select('category_id')
                            ->distinct()
                            ->get();

// Merge with id of 0 to avoid error in the next query if no relationships are found
$relationshipIds = array_merge([0], array_fetch($relationshipIds, 'category_id'));

return $this->model
            ->with($this->relationships)
            ->orderBy($orderBy, $sort)
            ->whereNotIn('id', $relationshipIds)
            ->paginate(Config::get('intranet.pagination.per_page'));

As you can see in the first half I fetch all the unique category ids from the pivot table that are children and in the second query I fetch the categories from that are not in the previous results.

Is it possible to some how include this in just one query? I would like to keep this contained within eloquent.

Thanks

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥100 set_link_state
    • ¥15 虚幻5 UE美术毛发渲染
    • ¥15 CVRP 图论 物流运输优化
    • ¥15 Tableau online 嵌入ppt失败
    • ¥100 支付宝网页转账系统不识别账号
    • ¥15 基于单片机的靶位控制系统
    • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
    • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
    • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
    • ¥15 手机接入宽带网线,如何释放宽带全部速度