0
votes

i have three database tables

  1. category (id,name)
  2. subcategory (id,name,category_id) foreign_key category_id on table category(id).
  3. subject(id,name,subcategory_id) foreign_key subcategory_id on table subcategory (id).

i want a row containing the following -

subject_id subject_name category_name subcategory_id

how to do this using eloquent .and if approach is wrong .please suggest a good method to achieve the same .

1
Could you post the code that you have?Wael Showair
i cant post large codes here now am using this to display subcategory $subcategory= Subcategory::with('category')->get(); public function category(){ return $this->belongsTo('App\Category'); } .Omsun Kumar

1 Answers

0
votes

Assuming you have the following models:

// 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');
  }      
}

You can get the data in your controller as follows:

// 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;
}

Edit for Laravel 5.1 Your models will be defined differently. Here's an example. Or follow the 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');
  }
}

Edit: Completed the functions with return statements as requested in comment