簡體   English   中英

laravel雄辯的一對多關系

[英]One to Many to One relationship in laravel eloquent

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

您要顯示什么樣的結果? 您想列出某個公司的員工及其摩托車的清單嗎?

也許您可以返回這樣的查詢。

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

您的代碼中有很多問題。 首先,例如,您編寫了class company extends Model但在控制器中您使用Company $company 同樣對於班級員工class employee extends Model但在motoCycle類中return $this->belongsTo('App\\Model\\Employee'); 對模型名稱使用首字母大寫等命名約定。 其次,我m not sure but I don認為您可以鏈接這樣的雄辯方法,例如: return $company->employee()->offset(0)->limit(20)->motorCycle()->get(); 偏移量和限制應在鏈的末尾。 也使用(Employee::class)代替('App\\Model\\Employee')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM