【发布时间】:2016-02-18 03:58:43
【问题描述】:
我正在尝试结合两个功能: - 得到一个随机模型 - ...但前提是它至少有 1 个相关模型
我的网址是entity/random
下面的代码运行良好:
if ($entityid == 'random') {
$random = Entity::all()->random(1);
return Redirect::to(trans('routes.entities') . '/' . $random->id);
}
现在,我的Entity 模型定义了两个关系:
public function comments()
{
return $this->hasMany('App\Models\Comment', 'entity_id');
}
public function sources()
{
return $this->hasMany('App\Models\Source', 'entity_id');
}
定义它们后,我可以通过$object->comments->count() 或$object->sources->count() 获得相关cmets 的数量。
我的数据库是 MySQL。
我的大多数Entities 没有 cmets 也没有来源。
灵感来自Laravel Querying Relations Model::has('relation') doesn't work 我能够得到一个至少有 2 个 cmets 的随机模型:
$random = Entity::has('comments', '>=', DB::raw(2))->get()->random(1);
// produces an Entity with at least 2 comments
要做的事情
仅当两个关系计数(sources 或 comments)中的至少一个至少为 2 时,如何选择随机模型。
也许像orHas这样的东西存在?
【问题讨论】:
标签: mysql laravel random eloquent laravel-5.2