php - laravel 中的关系和 Blade

标签 php mysql laravel eloquent laravel-blade

我有 3 个表,如下所述。

Table 1(user): 
id    username   password  Name Age

Table 2(tasks):
id  task_name  description

Table 3(logs) 
id user_id task_id date hours

表关系:

user has_many logs
task has_many logs

logs belongs_to user 
logs belongs_to  task

我想要实现的是获取包含用户名、任务名、日期和时间的日志。

Controller :

return View::make('log.index')
            ->with('logs',log::all());

Blade 模板

@foreach($logs as $log)
             <tr>
                <td>{{$log->id}}</td>
                <td>{{$log->users()->name}}</td>
                <td>{{$log->tasks()->name}}</td>
            <tr>
@endforeach

但无法从相应的表中获取用户名和任务名。任何帮助表示赞赏。

最佳答案

更好的方法是在您的模型中定义反向 hasMany 关系,如记录 here

因此在您的日志模型中,您可能需要定义:

class Log extends Eloquent {
    protected $table = "logs";

    public function user(){
         return $this->belongsTo('User');
    }
    public function task(){
         return $this->belongsTo('Task');
    }
}

然后在您看来,您可以使用:

$log->user()->first()->name

或者更好,通过使用动态属性:

$log->user->name

关于php - laravel 中的关系和 Blade ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14480510/

相关文章:

php - 如何根据 RFC 2231 在 PHP 中对文件名进行编码?

php - 在 html 表单提交中隐藏 php 文件 url

mysql - 插入...选择,在哪里

MySQL 更新未更新

php - 什么是框架?什么是学说 2?

php - Laravel 排队作业,在执行时间之前执行它

php - 通过 PHP 将服务器端 .exe 的输出流式传输到本地 Python

php - 在 CentOS 问题上安装 PHP

php - 连接到 CommissionJunction token 时出错 : [60] SSL certificate problem: unable to get local issuer certificate

javascript - Laravel 按 href 提交删除表单