如何在laravel eloquent中建立一个Model类与另一个模型类文件夹的关系?

时间:2017-05-11 16:05:53

标签: laravel laravel-5.3 laravel-5.4 laravel-eloquent

文件夹结构:

app
|-Admin.php
|-Admin
     |
     |-Product.php





    Admin.php
    --------------------------------------------------------
    namespace App;

    use Illuminate\Foundation\Auth\User as Authenticatable;

    class Admin extends Authenticatable
    {
        public function erp()
        {
            return $this->belongsToMany(Admin\Product::class);
        }
    }
    -----------------------------------------------------------



    Product.php
    -----------------------------------------------------------
    namespace App\Admin;

    use Illuminate\Database\Eloquent\Model;

    class Product extends Model
    {

        protected $primaryKey = 'productcode';
        public $incrementing = false;

        public function updatedBy()
        {
            return $this->belongsTo(Admin::class);
        }
    }

-----------------------------------------------------------

但是找不到错误类'Admin :: class' 任何解决方案??

2 个答案:

答案 0 :(得分:5)

使用正确的命名空间:

管理模式:

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Admin\Product;

class Admin extends Authenticatable
{
    public function erp()
    {
        return $this->belongsToMany(Product::class);
    }
}

产品型号:

namespace App\Admin;

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

class Product extends Model
{

    protected $primaryKey = 'productcode';
    public $incrementing = false;

    public function updatedBy()
    {
        return $this->belongsTo(Admin::class);
    }
}

或者将模型的名称空间添加为字符串,例如App\Admin

答案 1 :(得分:2)

请查看您的姓名空间

Product.php
-----------------------------------------------------------
namespace App\Admin;

因此,当您致电Admin::class时,它意味着App\Admin\Admin::class 所以请改变你的关系。

class Product extends Model
{

    protected $primaryKey = 'productcode';
    public $incrementing = false;

    public function updatedBy()
    {
        return $this->belongsTo('App\Admin');
    }
}