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...
$comment = App\Comment::find(1); echo $comment->post->title; 在上面这个例子中,Eloquent 尝试匹配 Comment 模型的 post_id 与Post 模型的 id,Eloquent 通过关联方法名加上 _id 后缀生成默认外键,当然,你也可以通过传递自定义外键名作为第二个参数传递到 belongsTo 方法,如果你的外键不是 post_id,或者你...
默认情况下,Eloquent将调用belongsTo的关联方法名user作为关联关系$relation的值,并将$relation.'_id'作为默认外键名对应users表的id,如果表中没有相应列,又没有在定义关联关系的时候指定具体的外键,就会报错。 1.4 控制器中的调用 public function oneToOne(){ $user_account = User::find(1)->getAccount; $u...
$profile=UserProfile::findOrFail(2);$user=$profile->user; 打印$user用户信息如下: 同样,和hasOne方法一样,belongsTo方法也是遵循了默认的约定规则,其完整方法签名如下: 代码语言:javascript 代码运行次数:0 运行 AI代码解释 publicfunctionbelongsTo($related,$foreignKey=null,$ownerKey=null,$relation=null) ...
$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. ...
$phone = User::find(1)->phone; Eloquent 假定所关联的外键是基于模型的名称的。在这个前提下,Phone模型会自动的假定其拥有一个user_id外键。如果你希望修改这个惯例,你可以传递第二个参数到hasOne方法中: return $this->hasOne('App\Phone', 'foreign_key'); ...
the same two queries. The key difference is that with() eager loads the related model up front, immediately after the initial query (all(), first(), or find(x), for example); when using load(), you run the initial query first, and then eager load the relation at some later point....
$post = Post::find(1); $post->comments()->saveMany([ new Comment(['message' => 'First comment']), new Comment(['message' => 'Second comment']), ]);多层级渴求式加载在Laravel 中,你可以在一条语句中渴求式加载多个层级,在这个例子中,我们不仅加载作者关系,而且还加载作者模型上的国家关系。
Model::with(['relation'=>function($query){}])->get();//只查找符合条件的关联数据 Model::whereHas('relation',function($query){ ... })->get();//1对多关联,查找关联数据符合条件的数据 Model::whereNotExists(function($query){ $query->from('relation_table')->where(''); ...
$roles = App\User::find(1)->roles()->orderBy('name')->get();如前文提到那样,Eloquent 会合并两个关联模型的名称并依照字母顺序命名。当然你也可以随意重写这个约定。可通过传递第二个参数至 belongsToMany 方法来实现:return $this->belongsToMany('App\Role', 'user_roles');...