laravel eloquent 中的一对多对一关系

One to Many to One relationship in laravel eloquent

我有 companyemployeemotorCycle table。

一个公司有很多员工。一名员工拥有一辆摩托车

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

我想像下面这样在控制器中获取结果

   public function show(Company $company)
    {
        return $company->employee()->offset(0)->limit(20)->motorCycle()->get();

    }

我正在尝试浏览此 URL http://127.0.0.1:8000/api/comapanys/1

我的路线如下

Route::apiResource('comapanys', 'ComapanyController');

你的代码有很多问题。 首先,例如你写 class company extends Model 但在控制器中你使用 Company $company。同样适用于 class 员工 class employee extends Model 但在 motoCycle class return $this->belongsTo('App\Model\Employee'); 中。使用命名约定,例如模型名称的首字母大写。 其次,我m not sure but I don不认为你可以像这样 return $company->employee()->offset(0)->limit(20)->motorCycle()->get(); 链接 eloquent 方法。偏移量和限制应在链的末端。 还使用 (Employee::class) 而不是 ('App\Model\Employee')

您想显示什么样的结果?你想知道某个公司的员工名单和 his/her 摩托车吗?

你可以return这样的查询。

public function show(Company $company)
{
 return $company->employee()->with('motorCycle')->offset(0)->limit(20)->get();
}