首页 > 解决方案 > 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);
}

如果可能的话,只使用belongsToor函数?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'];
    }
}

标签: laravelmodeleloquent

解决方案


有两种方法可以做到这一点。

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();

}

推荐阅读