一对多的关系计数 - 访问关系的差异 [英] One to many relationship count - difference in accessing relationship
问题描述
我有一对多的关系 - 条目
可以有很多访问
。
I have one to many relation - Entry
can have many Visits
.
在我的条目
模型中我有以下方法:
In my Entry
model I have the following methods:
public function visits() {
return $this->hasMany ('Visit', 'entry_id','id');
}
public function visitsCount() {
return $this->hasMany('Visit', 'entry_id','id')
->selectRaw('SUM(number) as count')
->groupBy('entry_id');
}
在刀片中,我可以使用以下方式获取访问次数:
In Blade I can get number of visits for my entry using:
{{$entry->visits()->count() }}
或
{{ $entry->visitsCount()->first()->count }}
如果我要创建访问器获取访问次数可以定义:
If I want to create accessor for getting number of visits I can define:
public function getNrVisitsAttribute()
{
$related = $this->visitsCount()->first();
return ($related) ? $related->count : 0;
}
现在我可以使用:
{{ $entry->nr_visits }}
问题
Questions:
-
在一些例子中,我看到了这样定义这种关系: p>
In some examples I saw defining such relation this way:
public function getNrVisitsAttribute()
{
if (!array_key_exists('visitsCount', $this->relations)) {
$this->load('visitsCount');
}
$related = $this->getRelation('visitsCount')->first();
return ($related) ? $related->count : 0;
}
问题是:这与我所展示的简单方法有什么区别?在开始?它是更快/使用更少的资源还是...?
Question is: what's the difference between this and the "simple method" I showed at the beginning? Is it quicker/use less resource or ... ?
为什么这种方法在这种情况下不起作用? $相关
是 null
所以访问者返回 0
而使用简单的方法它返回正确的访问次数
Why this method doesn't work in this case? $related
is null
so accessor return 0
whereas using "simple method" it returns correct number of visits
我也尝试在 visitsCount
方法关系从 hasMany
到 hasOne
,但不会改变任何内容。 >
I've tried also changing in visitsCount
method relationship from hasMany
to hasOne
but it doesn't change anything.
推荐答案
1您的关系不起作用,因为您没有选择
外国人关键:
1 Your relation won't work because you didn't select
the foreign key:
public function visitsCount() {
// also use hasOne here
return $this->hasOne('Visit', 'entry_id','id')
->selectRaw('entry_id, SUM(number) as count')
->groupBy('entry_id');
}
2您的访问者应该具有与关系相同的名称,以使其有意义(这就是为什么我首先创建了这些访问器):
2 Your accessor should have the same name as the relation in order to make sense (that's why I created those accessors in the first place):
public function getVisitsCountAttribute()
{
if ( ! array_key_exists('visitsCount', $this->relations)) $this->load('visitsCount');
$related = $this->getRelation('visitsCount');
return ($related) ? $related->count : 0;
}
这个访问器只是一种方便的方法来调用count: p>
This accessor is just a handy way to call the count this way:
$entry->visitsCount;
而不是
$entry->visitsCount->count;
// or in your case with hasMany
$entry->visitsCount->first()->count;
所以与性能无关。
还要注意,它不是以不同的方式定义关系,它需要如上所述定义关系。
Also mind that it is not defining the relation differently, it requires the relation to be defined like above.
这篇关于一对多的关系计数 - 访问关系的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!