You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
protected static function boot()
{
parent::boot();
// Order by name ASC
static::addGlobalScope('order', function (Builder $builder) {
$builder->orderBy('name', 'asc');
});
}
#truy vấn điều kiện where
# where name AND email
\App\User::whereNameAndEmail('phanlyhuynh','[email protected]')->first();
# where name OR email
\App\User::whereNameOrEmail('huynh','[email protected]')->get();
#giá trị default cho relation
public function user()
{
return $this->belongsTo('App\User')->withDefault(function ($user) {
$user->name = 'Guest Author';
});
}
#cache dữ liệu
$value = Cache::remember('users', $minutes, function () {
return DB::table('users')->get();
});
$value = Cache::rememberForever('users', function () {
return DB::table('users')->get();
});
#Sử dụng fresh() để truy vấn database và lấy phiên bản mới của item hiện tại
$user = \App\User::first();
$user->name = "Something new";
$user = $user->fresh(); // chú ý rằng nó sẽ trả về giá trị mới, nó không ảnh hưởng tới model hiện tại
dump($user->name); // nó sẽ trả về tên gốc, gốc phải "Something newm"
#muốn rehydrate model đã tồn tại, chúng ta sử dụng refresh()
# first
public function latestPost()
{
return $this->hasOne(\App\Post::class)->latest();
}
#seconds
$users = Topic::with('latestPost')->get()->sortByDesc('latestPost.created_at');
see more here https://laravel-news.com/eloquent-tips-tricks