amber

amber

FastAdmin Personal Records - thinkphp Many-to-Many Association Restriction Field Display

title: FastAdmin Personal Records - thinkphp Many-to-Many Relationship Restrict Field Display
date: 2022-08-26 11:37:42
tags:
- FastAdmin
- Tutorial
category:
- FastAdmin

Introduction#

Complaining that thinkphp is simple when it's simple and complicated when it's complicated
There are only questions but no answers in the official website discussion
I don't know why the field() function is ineffective in many-to-many relationships, and I couldn't find any information about many-to-many relationships after searching for a long time
Here, taking "cards" as an example, only display id, des, and status
Record the solution

Two Ways to Restrict Field Display in Many-to-Many Relationships#

Originally used method one, but if there are many fields in the main table, it's troublesome to display them one by one. Consider how to only restrict the fields in the associated table
At first, when I saw others writing like this, it didn't work: $v->getRelation('cards')->visible(['id','des','status']);
It prompted an error: Call to a member function visible() on array
I printed $v->getRelation('cards'); and found that it's an array. I originally wanted to use foreach loop and then use visible
Then I thought of wrapping it with collection(), and it worked

<?php
            public function index()
            {
                $list = $this->model
                    ->with('cards')
                    ->select();
    
                foreach ($list as $k => $v){
    
                    //TODO Limit data display
                    //Method one
                    $v->visible(['id','name','cards.id','cards.des','cards.status']);
      
                    //Method two
                    collection($v->getRelation('cards'))->visible(['id','des','status']);
    
                    //Similarly, use hidden to hide fields
                    $v->hidden(['cards.pivot']);
                }
            }

Many-to-Many wherePivot Filtering Condition#

    public function cards()
    {
        //Only display associated information with status greater than 0
        return $this->belongsToMany('app\admin\model\PersonalCard','app\admin\model\GroupCard','cardID', 'groupID')
            ->wherePivot('status','>',0);
    }
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.