在关联关系中,如果创建子关系的记录中需要用到父关系的 ID ,那么使用 hasMany 比使用 belongsTo 更简洁。
// if Post -> belongsTo(User), and User -> hasMany(Post)...// Then instead of passing user_id...Post::create(['user_id'=>auth()->id(),'title'=>request()->input('title'),'post_text'=>request()->input('post_text'),]);// Do thisauth()->user()->posts()->create(['title'=>request()->input('title'),'post_text'=>request()->input('post_text'),]);
// Before Laravel 7Schema::table('posts',function (Blueprint $table)) { $table->unsignedBigInteger('user_id'); $table->foreign('user_id')->references('id')->on('users');}// From Laravel 7Schema::table('posts',function (Blueprint $table)) { $table->foreignId('user_id')->constrained();}// Or, if your field is different from the table referenceSchema::table('posts',function (Blueprint $table)) { $table->foreignId('created_by_id')->constrained('users','column');}
// in app/Models/User.phppublicfunctionroles(){return$this->belongsToMany(Role::class)->using(RoleUser::class)->withPivot(['team_id']);}// app/Models/RoleUser.php: notice extends Pivot, not ModeluseIlluminate\Database\Eloquent\Relations\Pivot;classRoleUserextendsPivot{publicfunctionteam() {return$this->belongsTo(Team::class); }}// Then, in Controller, you can do:$firstTeam =auth()->user()->roles()->first()->pivot->team->name;
// if your Book hasMany Reviews...$book =App\Book::first();$book->loadCount('reviews');// Then you get access to $book->reviews_count;// Or even with extra condition$book->loadCount(['reviews'=>function ($query) { $query->where('rating',5);}]);
// If you have a quiz and want to randomize questions...// 1. If you want to get questions in random order:$questions =Question::inRandomOrder()->get();// 2. If you want to also get question options in random order:$questions =Question::with(['answers'=>function($q) { $q->inRandomOrder();}])->inRandomOrder()->get();
classUser{publicfunctionposts() {return$this->hasMany(Post::class); }// with a getterpublicfunctiongetPublishedPostsAttribute() {return$this->posts->filter(fn ($post) => $post->published); }// with a relationshippublicfunctionpublishedPosts() {return$this->hasMany(Post::class)->where('published',true); }}
// BEFORE: the foreign key is taken from the Post model$post->author_id === $user->id;// BEFORE: An additional request is made to get the User model from the Author relationship$post->author->is($user);// AFTER$post->author()->is($user);
// MigrationsSchema::create('role_user',function ($table) { $table->unsignedId('user_id'); $table->unsignedId('role_id'); $table->timestamp('assigned_at');})// first param for the record id// second param for the pivot records$user->roles()->updateExistingPivot( $id, ['assigned_at'=>now()],);
classUserextendsAuthenticable {// Get most popular post of userpublicfunctionmostPopularPost() {return$this->hasOne(Post::class)->ofMany('like_count','max'); }}