由于我缺乏使用Laravel的经验,我很难理解为什么我可以获得Post模型变量,但是当我尝试调用它的方法时会抛出错误。我不知道是否是路由问题。这是基于Laravel starter site的Laravel引导程序启动站点。以下错误和RegisteredUserController如下所示。
Call to undefined method stdClass::url()
$posts = DB::table('posts')->join('registered_posts' , 'posts.id' , '=' , 'registered_posts.post_id')->get();
foreach($posts as &$post){
echo $post->id; //works fine
echo $post->url(); //breaks
echo '<br>';
}
这是帖子模型
<?php
use Illuminate\Support\Facades\URL;
class Post extends Eloquent {
/**
* Deletes a blog post and all
* the associated comments.
*
* @return bool
*/
protected $fillable = array('registered_post');
public function delete()
{
// Delete the comments
$this->comments()->delete();
// Delete the blog post
return parent::delete();
}
public function registered_post(){
return $this->registered_post;
}
/**
* Returns a formatted post content entry,
* this ensures that line breaks are returned.
*
* @return string
*/
public function content()
{
return $this->content;
}
/**
* Get the post's author.
*
* @return User
*/
public function author()
{
return $this->belongsTo('User', 'user_id');
}
/**
* Get the post's meta_description.
*
* @return string
*/
public function meta_description()
{
return $this->meta_description;
}
/**
* Get the post's meta_keywords.
*
* @return string
*/
public function meta_keywords()
{
return $this->meta_keywords;
}
/**
* Get the post's comments.
*
* @return array
*/
public function comments()
{
return $this->hasMany('Comment');
}
/**
* Get the date the post was created.
*
* @param \Carbon|null $date
* @return string
*/
public function date($date=null)
{
if(is_null($date)) {
$date = $this->created_at;
}
return String::date($date);
}
/**
* Get the URL to the post.
*
* @return string
*/
public function url()
{
return Url::to($this->slug);
}
/**
* Returns the date of the blog post creation,
* on a good and more readable format :)
*
* @return string
*/
public function created_at()
{
return $this->date($this->created_at);
}
/**
* Returns the date of the blog post last update,
* on a good and more readable format :)
*
* @return string
*/
public function updated_at()
{
return $this->date($this->updated_at);
}
}
以下是我正在使用的路线
Route::group(array('prefix' => 'registered', 'before' => 'auth'), function()
{
# Admin Dashboard
Route::post('registered', 'RegisteredUserController@getIndex');
Route::controller('/', 'RegisteredUserController');
});
提前谢谢!
答案 0 :(得分:1)
您当前正在使用查询构建器,但期望获得Eloquent结果。使用DB::table
,您的结果将只包含裸对象而不是模型(具有url()
等函数)
你可以试试这个
$posts = Post::join('registered_posts' , 'posts.id' , '=' , 'registered_posts.post_id')->get();
您可能还希望将已注册的帖子定义为关系,然后将其加载为
$posts = Post::with('registeredPosts')->get();