laravel雄辩的一对多关系

时间:2018-06-30 07:59:34

标签: laravel eloquent relationships

我有companyemployeemotorCycle表。

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

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

2 个答案:

答案 0 :(得分:1)

您要显示什么样的结果?您想要列出某家公司的员工及其摩托车的清单吗?

也许您可以返回这样的查询。

if (this.keywords_val !== ''){
    var regex = new RegExp(this.keywords_val, "gi");
    if (degrees[i].keywords.replace(/ /g, '').match(regex)) check_keyword = true;
    else check_keyword = false;
}
if ((check === true) && (check_keyword === true)) matches.push(degrees[i]);
else nonmatches.push(degrees[i].name.replace(/ /g, ''));

答案 1 :(得分:0)

您的代码中有很多问题。  首先,例如,您编写@ViewChild(MatPaginator) paginator: MatPaginator; ngOnInit() { ... this.paginator._intl.itemsPerPageLabel = 'My translation for items per page.'; ... } ,但在控制器中使用class company extends Model。同样适用于班级雇员Company $company,但在motoCycle班级class employee extends Model中。对模型名称使用首字母大写等命名约定。 其次,我return $this->belongsTo('App\Model\Employee');认为您不能像这样的m not sure but I don链接雄辩的方法。偏移量和限制应在链的末尾。 同时使用return $company->employee()->offset(0)->limit(20)->motorCycle()->get();代替(Employee::class)