简体   繁体   中英

eloquent select all table with relationship many to many

I have 3 tables (workflow, user, workflow_user) and I would like to select the view column of the workflow_user table.

class Workflow extends Model
{

    public function user()
    {
        return $this->belongsToMany(User::class,'workflow_user');
    }
}
class User extends Model
{

    public function works()
    {
        //return $this->belongsToMany(Role::class);
        return $this->belongsToMany(Workflow1::class,'workflow_user');
    }
}

workflow_user table

class WorkflowUser extends Model
{

    protected $table = 'workflow_user';
    
    protected $fillable = [
        'workflow1_id','user_id','view'
    ];

    protected $primaryKey = 'id';
    
    public $timestamps = false;
}

To get the data from the workflow_user table I do this

$workflow = User::find($idconnect)->works()->orderBy('created_at','desc')->paginate(10);

When I make this request it does not give me the data of the workflow_user(workflow1_id,user_id,view) table.

If you have a model for the pivot table, you should have it extend the Pivot class and use it in the relationship's definition.

Also, you need to manually include the fields that are not the foreign ids in the query result.

class Workflow extends Model
{
    public function user()
    {
        return $this->belongsToMany(User::class, 'workflow_user', 'workflow_id', 'user_id')
                    ->using(WorkflowUser::class)
                    ->withPivot(['id', 'view']);
    }
}
class User extends Model
{
    public function works()
    {
        return $this->belongsToMany(Workflow::class, 'workflow_user', 'user_id', 'workflow_id')
                    ->using(WorkflowUser::class)
                    ->withPivot(['id', 'view']);
    }
}

workflow_user table

class WorkflowUser extends Pivot
{
    protected $table = 'workflow_user';    
    protected $fillable = ['workflow_id', 'user_id', 'view'];
    protected $primaryKey = 'id';
    public $incrementing = true;
    public $timestamps = false;
}
$workflow = User::findOrFail($idconnect)
                ->works()
                ->orderBy('created_at', 'desc')
                ->paginate(10);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM