用户模型
class User extends Authenticatable
{
use HasApiTokens,HasFactory, Notifiable;
protected $table = "users";
protected $primaryKey = 'ID';
public function scopeActive($query)
{
return $query->where('activated', 1);
}
public function followings()
{
return $this->hasMany('App\Models\Contacts','user_id','ID')->active();
}
联系人模型
class Contacts extends Model
{
use HasFactory;
protected $table = "contacts";
protected $primaryKey = 'ID';
public function user()
{
return $this->belongsTo(User::class, 'user_id', 'ID');
}
当我在 Tinker 上调用User::find(1)->followings()->count() 时,我得到
BadMethodCallException with message 'Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::active()'
如何获得仅激活 = 1 的关注者?
我通过向联系人模型添加自定义范围来修复它
public function scopeActiveFollowings($query)
{
return $query->join('users', function($join)
{
$join->on('users.ID', '=', 'contacts.contact_id')
->where('activated', '=', 1);
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句