【发布时间】:2017-02-16 10:31:05
【问题描述】:
我正在使用 Laravel 5.3 并尝试使用连接从多个表中返回数据。
我正在使用 3 个模型/表,客户、业务和网站,它们的相关性如下:
在 Customer.php 中:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
public function businesses()
{
return $this->hasMany('App\Business');
}
}
在 Business.php 中:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Business extends Model
{
public function customer()
{
return $this->belongsTo('App\Customer');
}
public function websites()
{
return $this->hasMany('App\Website');
}
}
在 Website.php 中:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Website extends Model
{
public function business() {
return $this->belongsTo('App\Business');
}
}
所以Customer 可以有很多Businesses,而Websites 可以有很多Websites。
现在我正在尝试使用 join 语句返回客户列表及其相关业务和网站信息。我正在使用以下代码返回此信息:
$customers = \DB::table('customers')
->join('businesses', 'customers.id', '=', 'businesses.customer_id')
->join('websites', 'businesses.id', '=', 'websites.business_id')
->select('customers.x', 'businesses.y', 'websites.z')
->get();
我希望数据以关联客户数组的数组返回,业务和网站数据嵌套在关联数组中,如下所示:
[
0 => {
$customer1Data,
$customer1BusinessData,
$customer1WebsiteData
}
1 => {
$customer2Data,
$customer2BusinessData,
$customer2WebsiteData
}
...
]
如果客户有一个企业有一个网站,但假设 $customer1 有两个企业,那么上面的连接会以这种格式返回一些东西:
[
0 => {
$customer1Data,
$customer1BusinessData1,
$customer1WebsiteData
}
1 => {
$customer1Data,
$customer1BusinessData2,
$customer1WebsiteData
}
...
]
有没有办法可以修改连接语句以这种格式返回该场景:
[
0 => {
$customer1Data,
businesses => {
$customer1BusinessData1,
$customer1BusinessData2
}
...
}
]
有没有办法通过连接语句实现这一点?或者我应该以不同的方式解决这个问题?任何帮助将不胜感激,非常感谢。
【问题讨论】:
-
你还没有完全使用雄辩。您可以只使用 ` $customer = Customer::with('business', 'business.websites')->all() ` 这将加载所有客户及其业务及其网站。所以你可以简单地使用`$customer->business`来获取所有的业务和一个嵌套循环来获取企业的网站。
标签: php mysql laravel eloquent