laravel model基本使用方法

model 基本方法
“`

$orders = App\Models\TestModel::all();

foreach (ordersasordersasorder) { $order->users->get();}

如果一个订单有25个用户,将导致有26条SQL语句,使用with可解决这个问题

Book::with(‘user’)->get();
Book::with(‘author’, ‘publisher’)->get();
Book::with(‘author.contacts’)->get();

// 约束急切的负载
User::with([‘posts’ => function (query) {query) {query->where(‘title’, ‘like’, ‘%first%’);
}])->get();

// 懒惰渴望加载
books=App\Book::all();books=App\Book::all();books->load(‘author’, ‘publisher’);
books>load([author=>function(books−>load([′author′=>function(query) {
$query->orderBy(‘published_date’, ‘asc’);
}]);

// 创建数据, created_at,updated_at会自动赋值
// 质量分配:fillable属性代表可赋值字段,guarded代表不可赋值字段
// 支持Array和Model
$user = User::create([]);

// 插入数据
$user = User::insert([]);

// 保存数据, created_at,updated_at会自动赋值
user=newUser;user=newUser;user->name=’a’; $user->save();

// 保存数据
comment=newApp\Comment([message=>Anewcomment.]);comment=newApp\Comment([‘message′=>‘Anewcomment.′]);post = App\Post::find(1);
post>comments()>save(post−>comments()−>save(comment);

// 保存数据
post=App\Post::find(1);post=App\Post::find(1);post->comments()->saveMany([
new App\Comment([‘message’ => ‘A new comment.’]),
new App\Comment([‘message’ => ‘Another comment.’]),
]);

// 创建数据
post=App\Post::find(1);post=App\Post::find(1);comment = $post->comments()->create([
‘message’ => ‘A new comment.’,
]);

// 先查找是否存在,不存在则添加数据,最后返回模型
User::firstOrCreate([‘name’ => 2]);

// 先查找是否存在,不存在返回模型,需要调用save添加
User::firstOrNew([‘name’ => 2]);

// 先查找是否存在数据,存在则更新,不存在则添加,最后返回模型
User::updateOrCreate([‘name’ => 2], [‘price’ => 99]);

// 更新数据,updated_at时间戳会自动更新
user=newUser::find(1);user=newUser::find(1);user->name=’a’; $user->save();

// 更新数据,updated_at时间戳会自动更新
User::where(‘name’, 1)->update([‘name’ => 2]);

// 删除模型, 分软删除和硬删除
user=newUser::find(1);user=newUser::find(1);user->delete();

// 删除数据, 分软删除和硬删除
App\Flight::destroy(1);
App\Flight::destroy([1, 2, 3]);
App\Flight::destroy(1, 2, 3);

// 永久删除模型,这个不管是软删除
$flight->forceDelete();

// 转换一个模型为数组
user>toArray();user−>toArray();user->toJson();

// 暂时修改属性可见性
$user->makeVisible(‘attribute’)->toArray();

// 暂时修改属性不可见性
$user->makeHidden(‘attribute’)->toArray();

*/“`

你可能感兴趣的:(php,laravel)