How to append or attach a pivot relationship to a model?

穿精又带淫゛_ 提交于 2021-02-11 15:37:33

问题


I am trying to get the practice area record of lawyers from practice_areas table along side each time I get a lawyer's record from lawyer_profiles_table. This two tables (practice_areas and lawyer_profiles) are related with a pivot table named (lawyer_practice_area)

This code below are from the LawyerProfile Model

public function practice_areas()
    {
        return $this->belongsToMany(PracticeArea::class, "lawyer_practice_area", "practice_area_id", "lawyer_id");
    }

I tried getting it through an attribute by doing the below

public function getPracticeAreasAttribute()
{
    return $this->practice_areas();
}

and then appended it this way

protected $appends = ["practice_areas"];

but I keep getting this result on postman - "withtimestamps":"false"

See output below:-

 "id": 1,
        "city": "Hintztown",
        "state": "Iowa",
        "longitude": "-163.884102",
        "latitude": "-18.127927",
        "lawyer_profile": {
            "id": 26,
            "email": "serena.barrows@yahoo.com",
            "name": "Raoul Hegmann",
            "primary_location_id": 1,
            "photo_id": 39,
            "phone_number": "887.299.6204 x456",
            "about_lawyer": "Distinctio eos omnis autem error.",
            "practice_areas": {
                "withTimestamps": false
            }
        }
    },

回答1:


Probably what you want to use is Eager loading.

Take a look at the documentation.

$books = App\Book::with('author')->get();

foreach ($books as $book) {
    echo $book->author->name;
}


来源:https://stackoverflow.com/questions/61296052/how-to-append-or-attach-a-pivot-relationship-to-a-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!