laravel one to many relationship example

Model =  Father.php


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\Child;

class father extends Model
{
    public function child()
    {
       //return $this->hasOne('App\Child');
       return $this->hasMany('App\Child');
    }
}

Model =  Child.php


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;


class child extends Model
{
protected $table = 'childs';
public function father()
{
return $this->belongsTo('App\Father');
}
}

Controller =   FatherController.php


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Father;
use App\Child;




class FatherController extends Controller
{
 public function index()
 {

  //echo "bhargav";exit;
//$child = Father::find(1);
$father = Father::with("child")->find(1);
//$child = Child::find(1);
//print_r($father->toArray());
echo "<pre>";print_r($father->toArray());
exit;


 }

}

No comments

Note: only a member of this blog may post a comment.