Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I establish a relationship a Model class with another model class of folder in laravel eloquent??

Folder Structure:

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

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

But got an error Class 'Admin::class' not found any solution??

like image 429
Sabyasachi Ghosh Avatar asked May 11 '17 16:05

Sabyasachi Ghosh


People also ask

What is polymorphic relationship laravel?

A one-to-one polymorphic relationship is a situation where one model can belong to more than one type of model but on only one association. A typical example of this is featured images on a post and an avatar for a user. The only thing that changes however is how we get the associated model by using morphOne instead.

What is hasMany in laravel?

hasMany relationship in laravel is used to create the relation between two tables. hasMany means create the relation one to Many. For example if a article have comments and we wanted to get all comments of the article then we can use hasMany relationship .

Does laravel have one relation?

hasOne relationship in laravel is used to create the relation between two tables. hasOne means create the relation one to one. For example if a article has comments and we wanted to get one comment with the article details then we can use hasOne relationship or a user can have a profile table.


1 Answers

Use correct namespaces:

Admin model:

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

Product model:

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

Or add namespace of a model as string, for example App\Admin

like image 57
Alexey Mezenin Avatar answered Oct 29 '22 01:10

Alexey Mezenin