如何解决在Laravel中创建“列表"模型的问题? [英] How to get around creating a 'List' model in Laravel?

查看:72
本文介绍了如何解决在Laravel中创建“列表"模型的问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎列表"是Laravel的某个关键字(或者PHP本身,我不确定.我是Laravel的新手.)

Seems like 'List' is a certain keyword for Laravel (or PHP itself, I'm not sure.. I'm new to Laravel).

我的数据库中有一个名为lists的表.在该表中有一个名为title的字段.另外,还有一个名为tasks的表,其中的list_id列引用了lists中的id列,所以我现在要做的是:

I have a table in my database called lists. Within that table there's a field called title. Also, a table called tasks, with a list_id column referencing the id column from the lists, so what I'm doing for now is:

app/models/MyAppList.php

app/models/MyAppList.php

class MyAppList extends Eloquent {
    protected $table = 'lists';
    public function tasks() {
        return $this->hasMany('Task', 'list_id');
    }
}

app/models/Task.php

app/models/Task.php

class Task extends Eloquent {
    public function myapplist()   {
        return $this->belongsTo('MyAppList');
    }
}

app/routes.php

app/routes.php

Route::get('/', function() {
    $v = Task::find(1);
    dd($v->myapplist()->lists('title'));
});

这会很好地输出拥有该任务的列表的标题.

This outputs the title of the list that owns that task just fine.

我认为对模型进行命名间隔是可行的.在文件namespace MyApp;中,文件为List.php,类为List,然后:

I thought namespacing the model would work. The file would be List.php, the class would be List, inside the file namespace MyApp; and then:

app/routes.php

app/routes.php

Route::get('/', function() {
    $lists = MyApp\List::all()->lists('title');
    dd($lists);
});

但这是行不通的.

为了方便起见,如果我将单词"List"保留为文件名和类名,然后尝试:

To clariy, if I leave the word 'List' as the name of the file and the class and then I try:

app/routes.php

app/routes.php

Route::get('/', function() {
    $lists = List::all()->lists('title');

    dd($lists);
});

我得到:

Symfony \ Component \ Debug \ Exception \ FatalErrorException
syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM), expecting '('

如果我为类List命名空间:

Route::get('/', function() {
    $lists = Mdl\List::all()->lists('title');

    dd($lists);
});

我得到:

Symfony \ Component \ Debug \ Exception \ FatalErrorException
syntax error, unexpected 'List' (T_LIST), expecting identifier (T_STRING)

推荐答案

最好的解决方案是使用不同于List的Eloquent类模型名称,因为List是PHP中的保留关键字.

Best solution is to use different Eloquent class model name than List as list is reserved keyword in PHP.

这篇关于如何解决在Laravel中创建“列表"模型的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆