إذا كان الجدول لا يحتوي على حقول timestamp الإفتراضية وهي updated_at, created_at يجب إعلام الـ mode بذلك من خلال $temestamps=false
class Company extends Model{
public $timestamps = false;
}
مطوّر ويب وتطبيقات
أكواد قصيرة جاهزة للنسخ واللصق — حيل Laravel واستعلامات Eloquent وأدوات تختصر عليك الوقت في مشروعك القادم.
إذا كان الجدول لا يحتوي على حقول timestamp الإفتراضية وهي updated_at, created_at يجب إعلام الـ mode بذلك من خلال $temestamps=false
class Company extends Model{
public $timestamps = false;
}
إذا أردنا تغيير أسماء حقول timestamp الإفتراضية وهي created_at, updated_at إلى أسماء أخرى مثل create_time, update_time ، يجب تحديد ذلك بالموديل
class Role extends Model{
const CREATED_AT = 'create_time';
const UPDATED_AT = 'update_time';
}
إذا كان لدينا حقل ولا نريد أن يتم التعديل عليه، نستطيع وضع قيود من خلال Model مع إستخدام Mutator
class User extends Model{
public function setEmailAttribute($value){
if ($this->email) {
return;
}
$this->attributes['email'] = $value;
}
}
بالوضع الإفتراضي يتم البحث في لارافيل بإستخدام find, findOrFail في حقل id، لكن اذا كنا نريد تغيير هذا الحقل يجب إن يتم تحديد ذلك في الـ model
model
class Product extends Model{
protected $primaryKey = 'title';
//tell Laravel to use title as primary key
}eloquent
public function search(Request $request){
$user = Product::findOrFail($request->title);
return $user;
}
لتغيير تنسيق حقول timestamp نستطيع إضافة دوال لذلك في الـ model
public function getCreatedAtFormattedAttribute(){
return $this->created_at->format('H:i d, M Y');
}
public function getUpdatedAtFormattedAttribute(){
return $this->updated_at->format('H:i d, M Y');
}
نستطيع عمل ترتيب للبيانات OrderBy مباشرة من خلال العلاقات في الـ model
public function products(){
return $this->hasMany(Product::class);
}
public function productsByName(){
return $this->hasMany(Product::class)->orderBy('name');
}
إذا أردنا عند تحديث حقل أأن يتم تحديث updated_at للأب ، يمكن عمل ذلك من خلال إستخدام $touches، مثال :- عند إضافة تعليق على مقال post، نريد أن يتم تحديث تاريخ تعديل المقال نفسة، يتم ذلك من خلال إضافة $touches->post في comment model
class Comment extends Model{
protected $touches = ['post'];
}