PHP code example of weiwenhao / tree-ql

1. Go to this page and download the library: Download weiwenhao/tree-ql library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

weiwenhao / tree-ql example snippets


# app/Resources/PostResource



namespace App\Resources;

use Weiwenhao\TreeQL\Resource;

class PostResource extends Resource
{
    protected $default = [
        'id',
        'title',
        'user_id'
    ];

    protected $columns = [
        'id',
        'title',
        'user_id'
    ];

    protected $relations = [
        'comments',
        'user'
    ];

    protected $custom = [
        'liked'
    ];
    
    protected $meta = [
        
    ];
}


protected $relations = [
    'comments',
    'user' => CustomUserResource::class,
];

# UserResource.php



namespace App\Resources;

use Weiwenhao\TreeQL\Resource;

class UserResource extends Resource
{
    protected $default = ['id', 'nickname', 'avatar'];

    protected $columns = ['id', 'nickname', 'avatar', 'password'];
}


# Post.php



namespace App\Models;

class Post extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

protected $custom = [
    'liked' => function ($post) {
        // logic 
        return $bool;
    }
];
 

protected $custom = [
    'liked'
];

public function liked($post, $params)
{
    // logic 
    // return $bool;
}
 

protected $custom = [
    'liked'
];

protected $meta = [
    'test'
];
 
/**
 * @param $post
 * @param $params ["key1" => "value1", "key2" => "value2"]
 */
public function liked($post, $params)
{
    // logic
    // return
}

/**
 * @param $params ["key1" => "value1", "key2" => "value2"]
 */
public function test($params)
{
    // logic
    // return
}

# CommentResource.php



namespace App\Resources;

use Weiwenhao\TreeQL\Resource;

class CommentResource extends Resource
{
    protected $default = ['id', 'content', 'user_id', 'floor'];

    protected $columns = ['id', 'content', 'user_id', 'floor'];

    protected $relations = [
        'user',
        'replies' => [
            'resource' => CommentReplyResource::class,
        ]
    ];

    
    /**
     * test.com/api/posts/{post}?

/**
 * test.com/api/posts? PostResource, and the definitions and configurations are activated!!
 *
 * @return \Weiwenhao\TreeQL\Resource
 */
public function index()
{
    // $posts = Post::columns()->latest()->get(); Same support
    $posts = Post::columns()->latest()->paginate();

    // Equivalent to return PostResource::make($post, request('