$query->whereHas('relation', function ($query) { // 添加关联模型的查询条件 }); 在这里,relation是指父模型和关联模型之间的关系方法,可以是模型类中定义的任何关联关系,如belongsTo、hasOne、hasMany等。 使用whereHas方法,我们可以在关联模型上执行其他查询操作,例如使用where方法添加其他条件、使用orderBy方法...
}protectedfunctiongetPolymorphicFields(){$relation=$this->detail();return[$relation->getMorphType(),$relation->getForeignKey()]; } my Controller \App\Production\Models\Production::detailable(function ($query) {$query->whereDate('panen_future_date', '2017-02-08'); })->with('detail')->get...
$query->select('*')->from($table)->whereRaw("{$this->getTable()}.{$key} = {$table}.{$model->getKeyName()}") ->when($callable instanceof \Closure, $callable); }); }); return $query; } protected function getPolymorphicFields() { $relation = $this->detail(); return [$relatio...
第二个参数是当前模型类所属表的外键,在本例中是user_profiles表的user_id字段,拼接规则和hasOne那里类似,只不过这里是基于第四个参数关联关系名称$relation: 代码语言:javascript 复制 if(is_null($relation)){$relation=$this->guessBelongsToRelation();}...if(is_null($foreignKey)){$foreignKey=Str::snake...
has(), whereRelation() etc. do respect soft-deleted items. This is the query from a fresh Laravel installation: select * from `posts` where exists( select * from `comments` where `posts`.`id` = `comments`.`post_id` and `comments`.`deleted_at` is null ) and `posts`.`deleted_at...
我的搜索时基于Question Model的,发送的两条SQL中, 第一条SQL是查询了符合TYPE=1条件的QUESTION,LARAVEL对结果做了相应的缓存。(因为是基于QUESTION的MODEL,并且我使用了with(Relation)的语法)。 第二条Sql使用with(realtion)的语法是在给第一次的结果加载关联关系,所以这个问题就迎刃而解了。
如果要统计其它关联模型结果数量字段,可以依次类推,对应字段都是 {relation}_count 结构。注:实际开发中为了提高查询性能,我们往往是在 posts 表中冗余提供一个 comments_count 字段,每新增一条评论,该字段值加 1,查询的时候直接取该字段即可,从而提高查询的性能。
您可以在AppServiceProvider中的boot函数中使用Relation::morphMap方法注册「多态映射表」,或者使用一个独立的服务提供者注册。 多对多多态关联 数据表结构 除了传统的多态关联,您也可以定义「多对多」的多态关联。例如,Post模型和Video模型可以共享一个多态关联至Tag模型。使...
return$builder->whereIn($relation->getForeignKey(),$in->select($relation->getOwnerKey()));}elseif($relationinstanceofRelations\HasOne){return$builder->whereIn($this->getKeyName(),$in->select($relation->getForeignKeyName()));}thrownewException(__METHOD__." 不支持 ".get_class($relation)...
代码示例2 classGameextendsEloquent{// many more stuff here// relation without any constraints ...works finepublicfunctionvideos(){return$this->hasMany('Video');}// results in a "problem", se examples belowpublicfunctionavailable_videos(){return$this->videos()->where('available','=',1)->...