用于查询雄辩数据库的var转储时为空?

时间:2017-11-03 13:48:51

标签: php eloquent slim

我正在尝试var_dump与任务相关联的用户表,并且我正在

NULL

最终我试图获得一个任务并将其与用户关联,我不确定我是否正确。

这是在Slim中使用eloquent

<?php


namespace App\Controllers;

use Slim\Http\Request;
use Slim\Http\Response;
use Illuminate\Database\Capsule\Manager as DB;
use App\Models\Task;

use App\Models\User;

class TodosController extends BaseController
{

    public function getTodos($request, $response, $args)
    {
        // $sth = $this->db->prepare("SELECT * FROM tasks ORDER BY task");
        // $sth->execute();
        // $use = User::all();
        // below
        // $todos = DB::table('tasks')
   //             ->join('users', 'users.id', '=', 'tasks.user_id')
   //             ->get();

        $todos = User::find(1)->tasks()->first();

        var_dump($todos);

        return $this->c->view->render($response, 'todos.twig', ['todos' => $todos]);

    }

Todos.twig

{% extends "templates/layout.html" %}

{% block content %}
<h1>My Todos</h1>

<ol>
  {% for task in todos %}
        <div id="task{{task.id}}" class="myl" ng-controller="myCtrl">
        <li><h4>{{ task.task}}</h4></li>
        <small style="font-style:italic">{{task.created_at |date("m/d/Y")}}</small></br>
        <small style="font-style:italic">{{task.user.id}}</small></br>




    <button id="disappear" name="task" class="btn btn-sm btn-danger" ng-click="deleteTask({{task.id}})">Delete</button>



        </div>
    {% endfor %}

</ol>
{% endblock %}

已更新

这是我的其他代码文件的样子。

不确定为什么我会收到错误

用户模型

<?php

namespace App\Models;


use Illuminate\Database\Eloquent\Model;


class User extends Model 
{
    protected $table = 'users';
    protected $fillable = ['username', 'password'];
    public $timestamps = [];


    public function tasks()
    {
        return $this->hasMany('App\Models\Task', 'user_id');
    }
}

任务模型

<?php

namespace App\Models;


// use Slim\Views\Twig as View;
// use Interop\Container\ContainerInterface;

use Illuminate\Database\Eloquent\Model;

class Task extends Model
{

    protected $table = 'tasks';
    protected $fillable = ['task', 'user_id'];

    public $timestamps = [];


    public function user()
    {
        return $this->belongsTo('App\Models\User', 'user_id');
    }

}

更新

enter image description here

0 个答案:

没有答案