$comment = App\Comment::find(1); echo $comment->post->title; 在上面这个例子中,Eloquent 尝试匹配 Comment 模型的 post_id 与Post 模型的 id,Eloquent 通过关联方法名加上 _id 后缀生成默认外键,当然,你也可以通过传递自定义外键名作为第二个参数传递到 belongsTo
Model::with('relation:relation.id,relation.name')->get();//只查找关联数据的id,name字段 Model::with(['relation'=>function($query){}])->get();//只查找符合条件的关联数据 Model::whereHas('relation',function($query){ ... })->get();//1对多关联,查找关联数据符合条件的数据 Model::where...
$user=User::findOrFail(1);$post->author()->associate($user);$post->save(); 通过dissociate方法接触当前模型与所属模型之间的关联 $post->author()->dissociate();$post->save(); 空对象模型 publicfunction author() {return$this->belongsTo(User::class,'user_id','id','author')->withDefault(...
$profile=UserProfile::findOrFail(2);$user=$profile->user; 打印$user用户信息如下: 同样,和hasOne方法一样,belongsTo方法也是遵循了默认的约定规则,其完整方法签名如下: 代码语言:javascript 代码运行次数:0 运行 AI代码解释 publicfunctionbelongsTo($related,$foreignKey=null,$ownerKey=null,$relation=null) ...
Model::with(['relation'=>function($query){}])->get();//只查找符合条件的关联数据 Model::whereHas('relation',function($query){ ... })->get();//1对多关联,查找关联数据符合条件的数据 Model::whereNotExists(function($query){ $query->from('relation_table')->where(''); ...
$phone = User::find(1)->phone; Eloquent 假定所关联的外键是基于模型的名称的。在这个前提下,Phone模型会自动的假定其拥有一个user_id外键。如果你希望修改这个惯例,你可以传递第二个参数到hasOne方法中: return $this->hasOne('App\Phone', 'foreign_key'); ...
$data = MyClass::with([ 'learners' => function ($query) { $query->select() ->where('learner_relation.status', 1) ->orderBy('learner_relation.create_time', 'desc'); }, ]) ->find($id); 1. 2. 3. 4. 5. 6. 7. 8. ...
$user = App\User::find(1); foreach ($user->roles as $role) { // }当然,和所有其它关联关系类型一样,你可以调用 roles方法来添加条件约束到关联查询上:$roles = App\User::find(1)->roles()->orderBy('name')->get();正如前面所提到的,为了决定关联关系连接表的表名,Eloquent 以字母顺序连接...
问使用和makeHidden的Laravel模型EN对于模型的探索我们还将继续。上篇文章中,只是简单地通过模型操作了一...
$post = App\Post::find(1); $post->comments[0]->message = 'Message'; $post->comments[0]->author->name = 'Author Name'; $post->push();新增方法除了save 和saveMany 方法外,你还可以使用 create 方法。它接受一个属性数组,同时会创建模型并插入到数据库中。 还有, save 方法和 create 方法的...