(laravel 文档浏览记录)
model
model casting
给一个模型的属性 指定类型,不便后续模型操作 1
relationship
模型和 relationship 的关系是什么?一个 one-to-many relationship 里,比方 post hasMany comments,那么
1
$post 就会自带很多办法或 property 比方
use App\Models\Post;
$comments = Post::find(1)->comments;
foreach ($comments as $comment) {// ...}
2
Eloquent will automatically determine the proper foreign key column for the Comment model. By convention, Eloquent will take the “snake case” name of the parent model and suffix it with _id
. So, in this example, Eloquent will assume the foreign key column on the Comment model is post_id.
Once the relationship method has been defined, we can access the collection of related comments by accessing the comments
property.
3
Since all relationships also serve as query builders, you may add further constraints to the relationship query by calling the comments method and continuing to chain conditions onto the query.
$comment = Post::find(1)->comments()
->where('title', 'foo')
->first();
4
什么是 query builder
(initial query 1)
relationship 提供的 methods 是 query builder 1
Since relationships also serve as powerful query builders, defining relationships as methods provides powerful method chaining and querying capabilities.
$user->posts()->where('active', 1)->get();
relationship
Database tables are often related to one another. For example, a blog post may have many comments or an order could be related to the user who placed it.
1
relationship one-to-many relationship
a blog post has many comments
a comment belongs to a post
在 comments table 里有 post_id 栏位
1
relationship – 通过 belongsTo relationship
父模型更新子模型
在 a model 的视角,
通过 belongsTo relationship, a model “ 找到 ” 本人的子模型 (实际上找到的是 $post->comments() 这个 relationship) 并通过它追加一个属于本人的子模型(形成了新一个 belongsTo relationship, 保留在隐形的联表里? 因为一对多关系不须要显式的联表)。
1
use App\Models\Comment;
use App\Models\Post;
$comment = new Comment(['message' => 'A new comment.']);
$post = Post::find(1);
$post->comments()->save($comment);
The save method will automatically add the appropriate post_id value to the new Comment model 1. 至此 comment model 处理完毕了,存储在 comments table 的时候 post_id 栏位有值 —— 否则 post_id 栏位 缺值,这是不对的。
子模型自我更新
在 a child model 的视角,
通过 belongsTo relationship, a child model 关联到 a new parent model
// user belongs to an account
use App\Models\Account;
$user->account()->associate(Account::find(10));
$user->save();
// 这个叫做 to assign a child model to a new parent model, you may use the `associate` method. In this example, the User model defines a belongsTo relationship to the Account model. This `associate` method will set the foreign key on the child model.
// (对此 user, 更新了 users table 里的它的 account_id 栏位)
// a new parent model 是 account
// comment belongs to a post
use App\Models\Post;
$comment->post()->associate(Post::find(10));
$comment->save();
// a new parent model 是 post
// (对此 comment, 更新了 comments table 里的它的 post_id 栏位)