유창한 팁과 요령 - Laravel
// Instead of this
$article = Article::find($article_id);
$article->read_count++;
$article->save();
// You can do this
$article = Article::find($article_id);
$article->increment('read_count');
Article::find($article_id)->increment('read_count');
Article::find($article_id)->increment('read_count', 10); // +10
Product::find($produce_id)->decrement('stock'); // -1
public static function boot()
{
parent::boot();
self::creating(function ($model) {
$model->uuid = (string)Uuid::generate();
});
}
class User extends Model {
protected $table = 'users';
protected $fillable = ['email', 'password']; // which fields can be filled with User::create()
protected $dates = ['created_at', 'deleted_at']; // which fields will be Carbon-ized
protected $appends = ['field1', 'field2']; // additional values returned in JSON
}
protected $primaryKey = 'uuid'; // it doesn't have to be "id"
public $incrementing = false; // and it doesn't even have to be auto-incrementing!
protected $perPage = 25; // Yes, you can override pagination count PER MODEL (default 15)
const CREATED_AT = 'created_at';
const UPDATED_AT = 'updated_at'; // Yes, even those names can be overridden
public $timestamps = false; // or even not used at all
$users = User::where('approved', 1)->get();
$users = User::whereApproved(1)->get();
User::whereDate('created_at', date('Y-m-d'));
User::whereDay('created_at', date('d'));
User::whereMonth('created_at', date('m'));
User::whereYear('created_at', date('Y'));
{{ $post->author->name ?? '' }}
// we can assign default property values to that default model
public function author()
{
return $this->belongsTo('App\Author')->withDefault([
'name' => 'Guest Author'
]);
}
// Imagine you have this
function getFullNameAttribute()
{
return $this->attributes['first_name'] . ' ' . $this->attributes['last_name'];
}
$clients = Client::orderBy('full_name')->get(); // doesn't work
$clients = Client::get()->sortBy('full_name'); // works!
protected static function boot()
{
parent::boot();
// Order by name ASC
static::addGlobalScope('order', function (Builder $builder) {
$builder->orderBy('name', 'asc');
});
}
// whereRaw
$orders = DB::table('orders')
->whereRaw('price > IF(state = "TX", ?, 100)', [200])
->get();
// havingRaw
Product::groupBy('category_id')->havingRaw('COUNT(*) > 1')->get();
// orderByRaw
User::where('created_at', '>', '2016-01-01')
->orderByRaw('(updated_at - created_at) desc')
->get();
// Instead of
$users = User::all();
foreach ($users as $user) { }
// You can do
User::chunk(100, function ($users) {
foreach ($users as $user) {
// ...
}
});
$product = Product::find($id);
$product->updated_at = '2019-01-01 10:00:00';
$product->save(['timestamps' => false]);
$result = $products->whereNull('category_id')->update(['category_id' => 2]);
// you can pass an array of parameters to orWhere() “Usual” way
$q->where('a', 1);
$q->orWhere('b', 2);
$q->orWhere('c', 3);
$q->where('a', 1);
$q->orWhere(['b' => 2, 'c' => 3]);
몇 가지 기본 사항을 제시하려고 했지만 더 깊이 들어가려면 출처를 방문하십시오.
저와 함께 즐거우셨기를 바라며, 새로운 것을 찾는 여러분을 존경합니다.
Reference
이 문제에 관하여(유창한 팁과 요령 - Laravel), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/morcosgad/eloquent-tips-and-tricks-laravel-3n94텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)