在Laravel 5.7中,我已经读过Has Many Through documentation,但仍无法正确使用。
这是数据库:
Analytics
id
data
subscriber_id
Subscribers
id
city_id
Cities
id
name
我需要Google Analytics(分析)模型通过Analytics
和subscribers.id
从cities.name
获取数据
我做了什么:
连接的Analytics(分析)和订户模型
<?php
class Analytics extends Model
{
public function subscriber()
{
return $this->belongsTo('App\Models\Subscriber');
}
}
class Subscriber extends Model
{
public function analytics()
{
return $this->hasMany('App\Models\Analytics');
}
}
发出一个请求,该请求从Analytics
表中获取带有订阅者数据的数据:
$results = Analytics::where('survey_id', '4')
->with('subscriber')
->whereDate('created_at', '>=', $last_survey_date)
->orderBy('data')
->get();
如果有人对如何获得城市名称有任何想法,请分享。
答案 0 :(得分:0)
// maybe this will work for you?
class Analytics extends Model
{
public function subscriber()
{
return $this->belongsTo('App\Models\Subscriber');
}
public function cities() {
return $this->hasManyThrough('App\City', 'App\Subscriber');
}
}
答案 1 :(得分:0)
我不确定我是否正确理解您的要求。您是否要获取给定Analytics
的{{1}}中的所有Subscribers
?还是您想要分析用户的城市名称?无论哪种方式,这都是解决方案。
要获取给定城市用户的所有分析数据,
City
或者要获取分析记录的城市名称,您有两个选择。一种是使用Laravel渴望加载关系,这种方法虽然有效,但可能会将很多不必要的数据加载到内存中。
$city = 'Vienna';
$results = Analytics::query()
->with('subscriber')
->whereHas('subscriber', function ($query) use ($city) {
$query->whereHas('city', function ($query) use ($city) {
$query->where('name', $city);
});
})
->where('survey_id', '4')
->whereDate('created_at', '>=', $last_survey_date)
->orderBy('data')
->get();
另一种方法是自己联接表并仅选择必要的数据:
$results = Analytics::query()
->with('subscriber.city') // you can nest relationships as far as they go
->where('survey_id', '4')
->whereDate('created_at', '>=', $last_survey_date)
->orderBy('data')
->get();
foreach ($results as $analytics) {
$city = $analytics->subscriber->city->name;
}
请注意,您可以使用$results = Analytics::query()
->join('subscribers', 'subscribers.id', '=', 'analytics.subscriber_id')
->join('cities', 'cities.id', '=', 'subscribers.city_id')
->where('analytics.survey_id', '4')
->whereDate('analytics.created_at', '>=', $last_survey_date)
->orderBy('analytics.data')
->select('analytics.*', 'cities.name as city_name')
->get();
foreach ($results as $analytics) {
$city = $analytics->city_name;
}
,但这将覆盖select('analytics.*', 'cities.name')
表中选择的name
列(如果存在)。因此,最好将列别名与analytics
一起使用。
答案 2 :(得分:0)
感谢Nick Surmanidze和Namoshek的回答! 我发现昨晚的工作方式:
class Subscriber extends Model
{
public function analytics()
{
return $this->hasMany('App\Models\Analytics');
}
public function subscriberCity()
{
return $this->belongsTo('Modules\Directories\Entities\City', 'city_id', 'id');
}
}
class City extends Model
{
public function subscriber()
{
return $this->hasMany('App\Models\Subscriber');
}
}
所需的结果可以通过这种方式获得:
$results = Analytics::where('survey_id', '4')
->with(['subscriber' => function($i){
$i->with(['subscriberCity']);
}])
->whereDate('created_at', '>=', $last_survey_date)
->orderBy('data')
->get();