how to retrive data from multiple table in laravel eloquent

穿精又带淫゛_ 提交于 2021-01-27 06:46:36

问题


Model relation
---------------------
language.php
----
public function attributeDetail()
{
    return $this->hasMany(AttributeDetail::class, 'language_id');
}

attribute.php
----
public function attributeDetail()
{
    return $this->hasMany(AttributeDetail::class, 'attribute_id');
}

attributeDetail.php
----
public function language()
{
    return $this->belongsTo(Language::class);
}
public function attribute()
{
    return $this->belongsTo(Attribute::class);
}

I want to show the json object like this

{
  'attribute_id' => 101,
  'available_language' => [
    {'id' => 1,'language_name' => 'English'},
    {'id' => 2,'language_name' => 'French'}
  ],
}

table structure:

languages(`id`, `language_name`, `translate_version`, `is_default`, `status`);
attributes(`id`, `required`, `type`, `status`);
attributedetails(id`, `attribute_id`, `language_id`, `attribute_name`, `status`);

回答1:


Try somthing like this,

$results =  Attribute::select('id')->with(['attributeDetail.language' => function ($query) {
    $query->select('id', 'language_name');
}])->get();


来源:https://stackoverflow.com/questions/44018746/how-to-retrive-data-from-multiple-table-in-laravel-eloquent

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