如何将枢轴关系附加或附加到模型?

时间:2020-04-18 20:49:04

标签: php laravel eloquent orm backend

每当我从律师档案表格中获取律师记录时,我都会尝试从习俗区域表中获取律师的执业区域记录。这两个表(practice_areas和律师个人资料)与名为(lawyer_practice_area)的数据透视表相关

下面的代码来自LawyerProfile模型

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

我尝试通过以下操作通过属性获取它

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

然后以这种方式附加

protected $appends = ["practice_areas"];

但是我一直在邮递员那里得到这个结果-“ withtimestamps”:“ false”

请参见下面的输出:-

 "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 个答案:

答案 0 :(得分:1)

您可能想使用的是Eager loading

看看文档。

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

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