model 基本方法
“`
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();
*/“`