[英]Problem with Laravel Eloquent - relation not working
我是 Laravel 的初学者。 我在 Laravel 5.8 中有项目。
我有User
model:
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable;
use psCMS\Presenters\UserPresenter;
use scopeActiveTrait;
public static $roles = [];
public $dates = ['last_activity'];
// ...
public function scopeHistory()
{
return $this->hasMany('App\UserLoginHistory');
}
// ...
}
和UserLoginHistory
:
class UserLoginHistory extends Model
{
protected $quarded = ['id'];
public $timestamps = false;
protected $fillable = ['user_id', 'date_time', 'ip'];
public function user()
{
return $this->belongsTo('App\User');
}
}
我想通过这段代码显示用户登录历史:
User::history()->where('id', $idAdmin)->orderBy('id', 'desc')->paginate(25);
但它不起作用。
这个 function 不工作 - 我没有得到结果。
我该如何解决?
首先,您将您的关系定义为 scope(使用scope
关键字作为关系前缀)。 尝试将您的 model 关系更新为:
public function history()
{
return $this->hasMany('App\UserLoginHistory');
}
然后,根据您的查询,您似乎想要获取给定User
的所有UserLoginHistory
记录。 您可以通过两种方式(至少)完成此操作。
从UserLoginHistory
model 本身,通过外键值约束查询:
$userId = auth()->id(); // get the user ID here.
$results = UserLoginHistory::where('user_id', $userId)->paginate(15);
// ^^^^^^^ your FK column name
从User
model 使用您定义的关系:
$userId = auth()->id(); // get the user ID here.
$results = User::find($userId)->history;
第二种方法的缺点是您需要手动对结果进行分页。
在您的用户 model 中,您应该通过这种方式定义您的关系:
public function history()
{
return $this->hasMany('App\UserLoginHistory');
}
那么如果你想 select 和历史 model 你可以用WhereHas()方法做到这一点:
User::whereHas(['history'=>function($q) use ($idAdmin) {
$q->where('id',$idAdmin)
}])->orderBy('id', 'desc')->paginate(25);
你必须做这个改变
public function history()
{
return $this->hasMany('App\UserLoginHistory');
}
用法
$user = User::find($idAdmin);
$userHistories = $user->history()->latest()->paginate(25);
或获取所有历史记录的用户
User::with('history')->find($idAdmin);
// Post model
namespace App;
use App\User;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function categories()
{
return $this->belongsToMany('App\Category')->withTimestamps();
}
}
// Category model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function posts()
{
return $this->belongsToMany('App\Post')->withTimestamps();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.