Laravel Eloquent用于显示主题表中的行?

时间:2015-09-28 12:58:31

标签: laravel

我有三个数据库表

  1. 类别(id,名称)
  2. 子类别(id,name,category_id)table_ category(id)上的foreign_key category_id。
  3. subject(id,name,subcategory_id)foreign_key subcategory_id on table subcategory(id)。
  4. 我想要一行包含以下内容 -

    subject_id subject_name category_name subcategory_id

    如何使用雄辩的方法来做到这一点。如果方法是错误的。请提出一个很好的方法来实现同样的目的。

1 个答案:

答案 0 :(得分:0)

假设您有以下型号:

// Category Model
class Category extends \Eloquent {
  protected $table = "category";
  public function subcategory(){
    $this->hasMany('Subcategory','category_id');
  }
}

// Subcategory Model
class Subcategory extends \Eloquent {
  protected $table = "subcategory";
  public function category(){
    $this->belongsTo('Category', 'category_id');
  }
  pubic function subject(){
    $this->hasMany('Subject', 'subcategory_id');
  }
}

// Subject model
class Subject extends \Eloquent {
  protected $table = "subject";
  public function subcategory(){
    $this->belongsTo('Subcategory','subcategory_id');
  }      
}

您可以按如下方式获取控制器中的数据:

// for subject with id 1
public function getOneRow(){
  $subject = Subject::with('subcategory.category')->findOrFail(1);
  //subject_id = $subject->id
  //subject_name = $subject->name
  //subcategory_id = $subject->subcategory->id
  //category_name = $subject->subcategory->category->name
  return array("subject_name"=>$subject->name, "category_name"=>$subject->subcategory->id, "subcategory_name"=>$subject->subcategory->category->name);
}

// for all subjects
public function getOneRow(){
  $subjects = Subject::with('subcategory.category')->all();
  $out = array();
  foreach($subjects as $subject){
  // each row
  //subject_id = $subject->id
  //subject_name = $subject->name
  //subcategory_id = $subject->subcategory->id
  //category_name = $subject->subcategory->category->name
    $out[] = array("subject_name"=>$subject->name, "category_name"=>$subject->subcategory->id, "subcategory_name"=>$subject->subcategory->category->name);
  }
  return $out;
}

编辑Laravel 5.1 您的模型将以不同方式定义。这是一个例子。或者点击docs

// Category Model Laravel 5.1
use Illuminate\Database\Eloquent\Model;
class Category extends Model {
  protected $table = "category";
  public function subcategory(){
    $this->hasMany('Subcategory','category_id');
  }
}

编辑:根据评论

中的要求完成了包含return语句的函数