laravel - Laravel 5.7为每个孩子获取所有兄弟姐妹
问题描述
我想知道如何在 laravel 模型中获得孩子的所有兄弟姐妹?
我知道我可以用它$siblings = \App\Child::all()->where('parent_id', $parent_id)->where('id', $id);
来获取所有的孩子兄弟姐妹,但我想知道我是否可以用其他方式或更干净的方式?所以你可以在刀片视图中$child->siblings->full_name
这样称呼它。
但我想知道如何在model.php中使用它这样的东西
public function parent()
{
return $this->belongsTo(User::class);
}
如果可能的话,只使用belongsTo
or函数?hasMany
对不起,我英语不好,所以我不知道它叫什么,所以我可以在谷歌上搜索它。
编辑:: 添加 Child.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class Child extends Model
{
protected $guarded = [];
protected $dates = [
'birthdate',
'father_birthdate',
'mother_birthdate',
'guardian_birthdate',
];
public function parent()
{
return $this->belongsTo(User::class);
}
// I want to call this function only using $child->siblings (this one will show all the siblings)
// without passing the parent id
// to make it cleaner
public function siblings($parent_id)
{
return $this->all()->where('parent_id', $parent_id);
}
public function getAgeAttribute()
{
return Carbon::parse($this->attributes['birthdate'])->age;
}
public function getFullNameAttribute()
{
return $this->attributes['first_name'] . ' ' . $this->attributes['last_name'];
}
}
解决方案
有两种方法可以做到这一点。
1 创建以下方法:
public function sibling()
{
return $this->belongsTo(User::class)->where('parent_id', $this->parent_id);
}
2 使用单个查询:
$siblings = \App\Child::where('parent_id', $parent_id)->get();
希望这可以帮助
更新
第三种方式是:
public function scopeSiblings($query, $parent_id) {
return $query->where('parent_id', $parent_id)->get();
}
推荐阅读
- java - 为什么 PDF InputStream.read() 返回 -1?
- vue.js - 自动将新帖子添加到侧边栏
- git - 如何对他人的拉取请求执行拉取请求
- python - 使用 matplotlib 从 CSV 创建绘图失败
- javascript - 在这种情况下,我是否需要在 angularjs 中手动管理范围?
- prolog - SWI-prolog - 如何使用键盘快捷键或全局谓词清除终端屏幕?
- angular - 连接在收到角度握手响应之前关闭
- c# - C# WPF - 从工作线程访问在 UI 线程上创建的对象而不阻塞
- android - 支持的最低 Gradle 版本为 4.6
- java - 使用 Spring Boot 后端处理从 Angular 4 上传的 Multipart CSV 文件?