laravel model基本使用方法

5 篇文章 0 订阅

model 基本方法
“`

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

foreach ( ordersas o r d e r s a s order) { $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(); b o o k s = A p p \Book :: a l l ( ) ; books->load(‘author’, ‘publisher’);
books>load([author=>function( b o o k s − > l o a d ( [ ′ a u t h o r ′ => f u n c t i o n ( 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; u s e r = n e w U s e r ; user->name=’a’; $user->save();

// 保存数据
comment=newApp\Comment([message=>Anewcomment.]); c o m m e n t = n e w A p p \Comment ( [ ‘ m e s s a g e ′ => ‘ A n e w c o m m e n t . ′ ] ) ; post = App\Post::find(1);
post>comments()>save( p o s t − > c o m m e n t s ( ) − > s a v e ( comment);

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

// 创建数据
post=App\Post::find(1); p o s t = A p p \Post :: f i n d ( 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); u s e r = n e w U s e r :: f i n d ( 1 ) ; user->name=’a’; $user->save();

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

// 删除模型, 分软删除和硬删除
user=newUser::find(1); u s e r = n e w U s e r :: f i n d ( 1 ) ; user->delete();

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

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

// 转换一个模型为数组
user>toArray(); u s e r − > t o A r r a y ( ) ; user->toJson();

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

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

*/“`

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值