php - 拉拉维尔 : Querying and accessing child objects in nested relationship with where clauses Many to Many relationship

标签 php mysql laravel-5 eloquent

您好,我在进行 Laravel 查询时遇到问题

模型区域

class Region extends Model
{
    protected $table = 'regions';

    protected $guarded = [

    ];

    public function county()
    {
        return $this->belongsTo('App\Models\County');
    }


    public function companies()
    {
        return $this->belongsToMany('App\Models\CompanyInfo', 
        'region_company','region_id','company_id');
    }

型号类别

class Category extends Model
{
    protected $table = 'categories';

    protected $guarded = [];


    public function companies()
    {
        return $this->belongsToMany('App\Models\Company', 'categories_company','category_id','company_id');
    }
}

模范公司

class Company extends Model
{

    protected $table ='companies';

    protected $guarded = [

    ];

    public function regions()
    {
        return $this->belongsToMany('App\Models\Region', 'region_company','company_id','region_id');
    }

}

我有一个输入表单,我想按类别和地区进行过滤,如果可能的话,输出应该是包含公司的类别,但我只想每个类别显示 10 家公司。不确定这是否可能。

这是我到目前为止所拥有的

$categories = $request->input('categories');

    $region = $request->input('regions');

    $companies = Category::whereIn('id',$categories)->with([
        'companies.regions' => function ($query) use ($region) {
            $query->whereIn('id', $region);
        }])->get();

这里的问题是它正在过滤类别,但它仍然给我所有公司没有过滤掉属于特定区域的一次。

谢谢 丹妮

最佳答案

尝试以下操作:

$categories = $request->input('categories');
$region = $request->input('regions');

$companies = Category::whereIn('id',$categories)->with([
    'companies' => function ($query) use ($region) {
        $query->whereHas('region', function ($q2) use ($region){
            $q2->whereIn('id', $region);
        });
        $query->with(['region']);
        $query->limit(10);
    }])->whereHas('companies', function($q) use ($region) {
        $q->whereHas('region', function ($q2) use ($region){
            $q2->whereIn('id', $region);
        });
    })->get();

关于php - 拉拉维尔 : Querying and accessing child objects in nested relationship with where clauses Many to Many relationship,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44701404/

相关文章:

php - Laravel 在不同环境下的细微差别

php - URL 路径重定向到单个 php 文件

php - 如何在 PHP 中获取完整的 URL,而不仅仅是其中的一部分?

mysql - 多对多关系的联接或多查询

php - 在外部存储过程中使用 MySQL 变量

Laravel 将模型类作为函数中的参数传递

javascript - 始终提交相同的表格

php - 有没有办法测试 php 代码是否兼容 php < 5.3.2

javascript - 当打开应用程序需要 iFrame 时欺骗引荐来源网址

php - 从 MySQL 表获取数据到 PHP 时,第一条数据不显示