问:我知道我可以通过以下方式定义关系
Class Users extends Model{
function profile(){
return $this->hasOne(Profile::Class);
}
}
有没有办法像向外关系和本地键以外的其他关系那样添加额外的查询以供定义,我只想获取字段active包含值的Profile模型的那些记录1。概要文件模型具有一个名为active的字段。任何帮助,想法将不胜感激,在此先感谢您。
答:你可以简单地尝试
return $this->hasOne(Profile::Class)->where('active', 1);
但更好的方法是
创建一个文件夹app / Scopes并添加一个新文件ActiveUserOnly.php
将此代码放在那里
命名空间App \ Scopes;
use \Illuminate\Database\Eloquent\Builder;
use \Illuminate\Database\Eloquent\Scope;
use \Illuminate\Database\Eloquent\Model;
class ActiveUsersOnly implements Scope {
/**
* @inheritdoc
*
* @param Builder $builder
* @param Model $model
*
* @return Builder|void
*/
public function apply( Builder $builder, Model $model ) {
return $builder->where( 'active', '=', true );
}
}
将此代码添加到您的Profile模型中。
protected static function boot() {
parent::boot();
static::addGlobalScope( new ActiveProfilesOnly() );
}
那么此代码将在您的用户模型中起作用。
班级用户扩展模型{
function profile(){
return $this->hasOne(Profile::Class);
}}