Laravel 调用成员函数时出错
我按照一些教程上,它只是不会工作。以下是我尝试过的: 榜样:Laravel 调用成员函数时出错,laravel,laravel-4,Laravel,Laravel 4,我按照一些教程上,它只是不会工作。以下是我尝试过的: 榜样: <?php class Role extends Eloquent { protected $table = 'accounts'; public function users() { return $this->belongsToMany('User'); } } 这是我的错误: Call to a member function contains() on a n
<?php
class Role extends Eloquent {
protected $table = 'accounts';
public function users()
{
return $this->belongsToMany('User');
}
}
这是我的错误:
Call to a member function contains() on a non-object
它说错误是在线的:
if ($roles->contains(3))
就像contains方法是。。。我不知道哈
另外,$roles=User::find(16)->group\u id代码>
16是帐户的id
,对吗?而组id
在表中
提前谢谢
编辑:
这是解决方案,我在RoleController.php
中对其进行了更改:
<?php
class RoleController extends BaseController {
public function get_role()
{
$roles = User::find(16)->group_id;
if (if ($roles == '1')
{
echo 'this works';
}
else
{
return Redirect::to('news/index');
}
}
}
这行:
$roles = User::find(16)->group_id;
表示您正在询问“查找用户16,并给我该用户的组id”。这就是你(在评论中)提到的“1”
由于您有组id
-更改
if ($roles->contains(3))
到
以下是解决方案,我在RoleController.php中对其进行了更改:
<?php
做一个print\r($roles)
看看你得到了什么我是这样做的:类RoleController扩展了BaseController{public function get\u role(){$roles=User::find(16)->group\u id;print\r($roles);}
它只显示了1:p,我还尝试用contain方法将它设置为1,但它仍然会出错。您的脚本希望$roles
是一个对象,如调试所示,$roles
包含1
(不是对象),这就是您出现错误的原因。啊哈,明白了。但我如何才能使它成为一个非对象,或者做任何能使它工作的事情呢?是否应该更改方法或其他内容?请尝试将角色中的公共函数用户()
(复数)更改为公共函数用户()
(单数)您可以更新您的答案以包括更改代码的位置吗?一个更大的片段(我知道你可以通过阅读问题来推断,但如果答案是自给自足的,那就更好了)
if ($roles->contains(3))
if ($roles == '3')
<?php
public function get_role() {
$roles = User::find(16)->group_id;
if (if ($roles == '1')
{
echo 'this works';
} else {
return Redirect::to('news/index');
}
}
}