Php 雄辩的多表数据和关系
我有三张桌子:Php 雄辩的多表数据和关系,php,mysql,laravel-5,Php,Mysql,Laravel 5,我有三张桌子: Schema::create('companies', function (Blueprint $table) { $table->increments('id'); $table->integer('city_id')->unsigned(); $table->string('name'); $table->string('address');
Schema::create('companies', function (Blueprint $table) {
$table->increments('id');
$table->integer('city_id')->unsigned();
$table->string('name');
$table->string('address');
$table->float('lat', 10,6);
$table->float('lng', 10,6);
$table->timestamps();
$table->foreign('city_id')->references('id')->on('cities');
});
Schema::create('company_clients', function (Blueprint $table) {
$table->increments('id');
$table->integer('company_id')->unsigned();
$table->integer('client_id')->unsigned();
$table->foreign('company_id')->references('id')->on('companies');
$table->foreign('client_id')->references('id')->on('companies');
});
Schema::create('cities', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
});
现在,我想要一个有说服力的查询,它将返回一个公司数组(不仅仅是一项),其中(例如)company_clients表上的company_id=1。此外,假设city_id使用cities表返回名称而不是id。我无法想象现在该怎么做。
我提出:
但是,我缺少控制器中的代码。我试过:
$result = Company::leftJoin('company_clients', function($join) {
$join->on('companies.id', '=', 'company_clients.company_id');
})->where('company_clients.company_id', '=', 1 )->get();
或
但是没有返回正确的结果。我错过了什么
谢谢
编辑:
我已经找到了一种方法,但我不确定这是不是最好的方法。有人能确认一下吗
$result = Company::join('company_clients', function($join) {
$user = Auth::guard('api')->user();
$join->on('companies.id', '=', 'company_clients.client_id')->where('company_clients.company_id', '=', $user->company_id );
})->join('cities', 'cities.id', '=', 'companies.city_id')->get(array('companies.*', 'cities.name'));
试一试
改名
公司
公司客户模型与企业价值的关系
公司
开始检查您的模式:
$table->foreign('client_id')->references('id')->on('companys')代码>。它不应该引用客户表吗?对于“公司”和“客户”,它是同一个表,只是因为数据完全相同。但是,这些公司之间有一种关系,我将其中一个列称为client_id,以显示一家公司可以有多个客户,这也是一家公司。这是一个好机会!结果是我所期望的,但json的格式很奇怪:我期望的是这样的:一旦这是一个演示,结果在所有条目中都是相同的,所以这并没有错。如果你把公司分开,效果会更好。因为从上面的查询中,它将查询每个客户的公司记录。CompanyClients::with('clients')->where('company_id',$company_id)->get();Company::with('city')->find($Company_id);然后您可以使用stdclass根据自己的喜好格式化json这是我无法理解的部分。从CompanyClients中,我需要运行一次以获取所有company_id=1的条目。在那之后,我只需要从companys表中获取信息,然后在一个几乎单独的电话中,在另一个表中获取城市的名称。我不明白为什么多给客户一张桌子会让它更有效率。顺便说一句,我上面做的代码(在主要问题的编辑部分)可以吗?我基本上做了两次内部连接,得到了结果。不确定这是否是一个好的做法。像这样的事情是的,这一次给了我一个非常好的方法。最后我做了一点修改,但是你的回答确实帮助我达到了最终的效果。老实说,我在项目的所有其他部分都使用了相同的方法,因为很清楚发生了什么。非常感谢。
$result = Company::with(['clients' => function($q){
$q->where('company_id', 1);
}])->get();
$result = Company::join('company_clients', function($join) {
$user = Auth::guard('api')->user();
$join->on('companies.id', '=', 'company_clients.client_id')->where('company_clients.company_id', '=', $user->company_id );
})->join('cities', 'cities.id', '=', 'companies.city_id')->get(array('companies.*', 'cities.name'));
CompanyClients::with('company.city', 'clients')->where('company_id', 1)->get();