Addison

7585 经验值

@JellyBool,本人在使用 dingo/api 组件时,不知道如何返回数据表的关联结果。特来请教。
先上代码。

    /**
     * 创建一个新用户,同时设置角色与所属部门
     * @Post("/")
     * @Versions({"v1"})
     * @Transaction({
     *      @Request({"name": "admin", "email": "[email protected]","phone":"18679152251","role_id":"2",
     *     "department_id":"1"},
     * headers={"Authorization": "Bearer  token_value"}),
     *      @Response(200, body={"data": {"id": 10, "username": "admin" ),
     *      @Response(500, body={"message": "xxx","code":"23000"})
     * })
     * @Parameters ({
     *      @Parameter("name", description="用户名",required=true),
     *      @Parameter("phone", description="用户手机.",required=true),
     *      @Parameter("email", description="用户邮箱.",required=true),
     *      @Parameter("role_id", description="角色 id.",required=true),
     *      @Parameter("department_id", description="部门 id.",required=true),
     * })
     * @param AddUserRequest $request 表单提交请求
     * @return \Dingo\Api\Http\Response|void
     */
    public function store(AddUserRequest $request)
    {
        $input = [
            'email' => $request->get('email'),
            'name' => $request->get('name'),
            'password' => password_hash(self::DEFAULT_PASSWORD, PASSWORD_DEFAULT),
            'role_id' => $request->get('role_id'),
            'department_id' => $request->get('department_id'),
            'phone' => $request->get('phone'),
        ];

        try{
            DB::transaction(function () use ($input){
                $user = User::create($input);

                $role = Role::findOrFail($input['role_id']);
                $user->attachRole($role);

                $department = Department::findOrFail($input['department_id']);
                $user->departments()->save($department);
            });

            $user = User::where('email','=',$input['email'])->with('departments')->with('roles')->get();

            return $this->response->item($user, new UserTransformer());

        }catch (Exception $e){
            return $this->response->errorInternal('用户创建失败');
        }

    }

其中,UserTransformer 代码如下:

class UserTransformer extends TransformerAbstract
{
    public function transform($user)
    {
        return [
            'id' => $user['id'],
            'name' => $user['name'],
            'email' => $user['email']
        ];
    }
}

在 UsersController 里的结果返回,我自己觉得使用如下代码是不对的。因为查询到的结果是3个表的关联查询后的结合。如何使用 Transformer 处理 这种情况。

return $this->response->item($user, new UserTransformer());

从 Illuminate\Database\Eloquent\Model 抽象基类的代码来理解可能会有帮助

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = [];

Eloquent 模型约定
除非数据表明确地指定了其它名称,否则将使用类的「蛇形名称」、复数形式名称来作为数据表的名称

视频中提到的

crontab -l 

应该是查看用户的 crontab 列表,不是执行定时任务。

usage:    crontab [-u user] file
    crontab [ -u user ] [ -i ] { -e | -l | -r }
        (default operation is replace, per 1003.2)
    -e    (edit user's crontab)
    -l    (list user's crontab)
    -r    (delete user's crontab)
    -i    (prompt before deleting user's crontab)

视频上有个遗漏,在系统中,在执行

crontab cron.txt

之前,建议执行(Ubuntu 为例)

/etc/init.d/cron status

如果返回

root@05034a881f5d:/app# /etc/init.d/cron status
 * cron is not running

则需要再执行

/etc/init.d/cron start

不然定时任务不会生效(本人遇到的实际情况)

@teddy, 如果是前端访问后台 restful 形式的api,验证没有通过的情况,可以参考 issue#584

我尝试了下,不运行 unguard() 方法也是可以得到期望的结果,但前提是 comment 模型类必须声明

 $fillable=['body'];

你这样使用unguard() 方法,是不是如这里所述的用法?Model-Eloquent 配置信息

// 关闭模型插入或更新操作引发的 「mass assignment」异常
 Eloquent::unguard();

引用下 Eloquent: 入门 里的原文,希望有帮助。

  1. 要在数据库中创建一条新记录,只需创建一个新模型实例,并在模型上设置属性和调用 save 方法即可。(但是需要 > 2 行代码实现)

  2. 你也可以使用 create 方法在一行代码上保存一个新模型。被添加的模型实例将会从你的方法中返回。然而,在这样做之前,你需要先在你的模型上指定一个 fillable 或 guarded 属性,因为所有的 Eloquent 模型都有针对批量赋值(Mass-Assignment)做保护。

  3. save 方法也可以用于更新数据库中已经存在的模型。要更新模型,则须先取回模型,再设置任何你希望更新的属性,接着调用 save 方法。

谢谢回复。按你的回复测试通过。
不过在PostsController里用采用如下示例代码。

<?php
namespace App\Http\Controllers;
use Illuminate\Contracts\Auth\Access\Gate;
use Illuminate\Http\Request;
use App\Http\Requests;

class PostsController extends Controller
{
    public function show($id)
    {
        $post = \App\Post::findOrFail($id);
        \Auth::loginUsingId(1);
        $this->authorize('show-post', $post);
//        if(Gate::denies('show-post',$post))
//        {
//            abort(403,'Sorry');
//        }
        return $post->title;
    }
}

如果采用注释里的代码的话,会报如下错误:
FatalThrowableError in PostsController.php line 18:
Non-static method Illuminate\Contracts\Auth\Access\Gate::denies() cannot be called statically
(看了下Gate类,denies()方法不是静态方法。)

5.3AuthServiceProvider下的boot()与视频不一致,请教实现