【问题标题】:How to append or attach a pivot relationship to a model?如何将枢轴关系附加或附加到模型?
【发布时间】:2020-04-18 20:49:04
【问题描述】:

每次我从lawyer_profiles_table 获取律师记录时,我都试图从practice_areas 表中获取律师的执业领域记录。这两个表(practice_areas 和lawyer_profiles)与一个名为(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
            }
        }
    },

【问题讨论】:

标签: php laravel eloquent orm backend


【解决方案1】:

你想用的可能是Eager loading

查看文档。

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

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

【讨论】:

  • 非常感谢,热切加载对我来说非常有效。
  • 我不必通过获取属性和附加来完成我之前所做的所有事情。我通过这种方式使用急切加载嵌套关系实现了我想要的,
猜你喜欢
  • 1970-01-01
  • 2014-08-17
  • 2016-01-23
  • 1970-01-01
  • 1970-01-01
  • 2019-11-23
  • 2021-01-08
  • 2014-06-07
  • 2021-08-25
相关资源
最近更新 更多