PHP's db class library Eloquent uses series (8) alone - many-to-many association

My Eloquent series of articles using
php's db class library Eloquent alone series (1)
php's db class library Eloquent alone series (2) - paging
php's db class library Eloquent alone series (3) - sql log
php db class library Eloquent used alone series (4) - event monitoring
php's db class library Eloquent used alone series (5) - model to array
php's db class library Eloquent used alone series (6) - one-to-one association with
php's db class Library Eloquent used alone series (7) - one-to-many association
php's db class library Eloquent used alone series (8) - many-to-many association
php's db class library Eloquent used alone series (9) - many-to-many association - table association
The db class library Eloquent of its own php uses the series (10) - many-to-many association - remote one-to-many
php db class library Eloquent uses the series (11) - many-to-many association - adding model attributes
php's db class library Eloquent Single use series (12) - result set model to array - 2



The purpose of this series of articles is to use Eloquent out of the laravel environment, because it is easy to use.
All codes in this series of articles have passed the test. Eloquent Version: 5.4.27

The purpose of this article is to use many-to-many associations.
First create a table, a user has multiple roles, and a role can correspond to multiple users. Need to build 3 tables to meet the demand.
CREATE TABLE users (
  id int(11) NOT NULL AUTO_INCREMENT,
  name varchar(50) NOT NULL DEFAULT '' COMMENT 'User name',
  age int(11) NOT NULL DEFAULT '0' COMMENT 'age',
  PRIMARY KEY (id)
);

CREATE TABLE roles (
  id int(11) NOT NULL AUTO_INCREMENT,
  name varchar(50) NOT NULL DEFAULT '' COMMENT 'Role name',
  PRIMARY KEY (id)
);

CREATE TABLE user_roles (
  id int(11) NOT NULL AUTO_INCREMENT,
  user_id int  NOT NULL DEFAULT 0 COMMENT '用户id',
  role_id int  NOT NULL DEFAULT 0 COMMENT '角色id',
  create_time int not null default 0 comment 'create time',
  PRIMARY KEY (id)
);


The source code
has a total of 3 files, the main program, the user model class, and the role model class. Note that there is no associated table model!
User.php
<?php
namespace app\model;
use \Illuminate\Database\Eloquent\Model;

/**
 * User model class
 */
class User extends Model
{
    protected $table = 'users';
    public $timestamps = false;
    
    public function roles()
    {
        // Important note: parameter 2 is the name of the association table, parameter 3 is the foreign key corresponding to this class in the association table, parameter 4 is the foreign key of parameter 1
        return $this->belongsToMany('app\model\Role', 'user_roles' , 'user_id', 'role_id')
            ->withPivot('create_time' );
    }
}


Role.php
<?php
namespace app\model;
use \Illuminate\Database\Eloquent\Model;

/**
 * Role model class
 */
class Role extends Model
{
    protected $table = 'roles';
    public $timestamps = false;
    
    public function users()
    {
        // Important note: parameter 2 is the name of the association table, parameter 3 is the foreign key corresponding to this class in the association table, parameter 4 is the foreign key of parameter 1
        return $this->belongsToMany('app\model\User', 'user_roles' , 'role_id', 'user_id')
            ->withPivot('create_time' );
    }
}


Main program:
<?php
namespace app\control;

use Illuminate\Database\Capsule\Manager;
use app\model\User;
use app\model\Role;

class Ill3
{
    /**
     * Main program.
     */
    public function index()
    {
        $db = new Manager ();
        $db->addConnection ( [
            'driver' => 'mysql',
            'host' => '127.0.0.1',
            'database' => 'test1',
            'username' => 'root',
            'password' => 'root',
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => ''
        ] );
        $db->setAsGlobal ();
        $db->bootEloquent ();
      
        $db::delete('delete from users ');
        $db::delete('delete from roles ');
        $db::delete('delete from user_roles ');
        
        $user = new User ();
        $user->name = 'User1';
        $user->id = 1;
        $user->save (); // new model added
        $user = new User ();
        $user->name = 'User2';
        $user->id = 2;
        $user->save (); // new model added
        
        $role = new Role();
        $role->id = 1;
        $role->name = 'Super Administrator';
        $role->save (); // new model added
        
        $role = new Role();
        $role->id = 2;
        $role->name = 'Administrator';
        $role->save (); // new model added
        
        $role = new Role();
        $role->id = 3;
        $role->name = 'Ordinary user';
        $role->save (); // new model added
        
        $db::table('user_roles')->insert([
            'user_id' => 1,
            'role_id' => 2,
            'create_time' => time(),
        ]);
        $db::table('user_roles')->insert([
            'user_id' => 1,
            'role_id' => 3,
            'create_time' => time(),
        ]);
        $db::table('user_roles')->insert([
            'user_id' => 2,
            'role_id' => 2,
            'create_time' => time(),
        ]);
        echo "<h2>All roles of user1</h2>";
        echo User::find(1)->roles->toJson(JSON_UNESCAPED_UNICODE);
        echo "<br>";
        
        echo "<h2>All users of role 2</h2>";
        echo Role::find(2)->users->toJson(JSON_UNESCAPED_UNICODE);
        echo "<br>";
        echo '<br>all ok!';
    }
}


Browser output


summary:
  • The field value of the intermediate table can be read through the pivot attribute
  • There is no need to build a model for the intermediate table
  • As before, methods are called without parentheses, and dynamic properties such as roles are called
  • toJson with parameters can avoid Chinese being encoded

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327039192&siteId=291194637