我只看到一个用户ID与我的待办事项关联,它应该提取一个用户名,即todo与用户关联,也许是我的控制器没有提取正确的信息或者可能是其他东西,这是使用苗条顺便说一句,口若悬河。
task.user_id.username
不起作用,task.user_id
确实显示与该用户关联的号码。
todos twig
{% extends "templates/layout.html" %}
{% block content %}
<h1>My Todos</h1>
<ol>
{% for task in tasks %}
<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.username}}</small></br>
<button id="disappear" name="task" class="btn btn-sm btn-danger" ng-click="deleteTask({{task.id}})">Delete</button>
</div>
{% endfor %}
</ol>
{% endblock %}
todos controller
public function getTodos($request, $response, $args)
{
$tasks = Task::with('user')->get();
return $this->c->view->render($response, 'todos.twig', ['tasks' => $tasks]);
}
答案 0 :(得分:0)
在这里看了一些其他帖子后,我将我的代码改为
我必须将我的模型类与user_id匹配,以便属于BOTH类,而不仅仅是一个。
user.php的
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $table = 'users';
protected $primaryKey = 'user_id';
protected $fillable = ['username', 'password'];
public $timestamps = [];
public function tasks()
{
return $this->hasMany('App\Models\Task', 'user_id');
}
}
Task.php
<?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');
}
}
从这里我可以像这样引用用户名
{% extends "templates/layout.html" %}
{% block content %}
<h1>My Todos</h1>
<ol>
{% for task in tasks %}
<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.username}}
</small>
</br>
<button id="disappear" name="task" class="btn btn-sm btn-danger" ng-click="deleteTask({{task.id}})">Delete</button>
</div>
{% endfor %}
</ol>
{% endblock %}