Reputation: 7052
I have company
, employee
and motorCycle
table.
One Company has many employee. One employee has One motorCycle
Company.php
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Company extends Model
{
protected $table = 'company';
protected $primaryKey = '_id';
public function employee()
{
return $this->hasMany(Employee::class);
}
}
?>
Employee.php
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
protected $table = 'employee';
protected $primaryKey = '_id';
public function motorCycle()
{
return $this->hasOne(MotorCycle::class, 'motorCycle', 'id');
}
}
?>
MotorCycle.php
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class MotorCycle extends Model
{
protected $table = 'motorCycle';
protected $primaryKey = 'id';
public function employee()
{
return $this->belongsTo('MotorCycle::class');
}
}
?>
I would like to fetch result in controller like below
public function show(Company $company)
{
return $company->employee()->offset(0)->limit(20)->motorCycle()->get();
}
I am trying to browse this URL http://127.0.0.1:8000/api/comapanys/1
My route is like below
Route::apiResource('comapanys', 'ComapanyController');
Upvotes: 0
Views: 955
Reputation: 411
what kind of result do you want to display? you want to have a list of employees and his/her motorcycle in a certain company?
may you can return a query like this.
public function show(Company $company)
{
return $company->employee()->with('motorCycle')->offset(0)->limit(20)->get();
}
Upvotes: 1
Reputation: 89
There is to many problem in your code.
First, for example you write class company extends Model
but in controller you use Company $company
. Also for class employee class employee extends Model
but in motoCycle class return $this->belongsTo('App\Model\Employee');
. Use naming convention like first letter uppercase for model name .
Second, im not sure but I don
t think you can chain eloquent methods like this return $company->employee()->offset(0)->limit(20)->motorCycle()->get();
. Offset and limit should be on the end of chain.
Also use (Employee::class)
instead of ('App\Model\Employee')
Upvotes: 0