php artisan tinker
Psy Shell v0.4.1 (PHP 5.4.16 — cli) by Justin Hileman
>>> AppArticle::first()->toArray();
=> [
"id" => "1",
"user_id" => "1",
"title" => "User 1 Article",
"body" => "User 1 Body",
"published_at" => "2015-03-31 08:00:00",
"created_at" => "2015-03-31 04:17:58",
"updated_at" => "2015-03-31 04:17:58",
"excerpt" => null
]
#获取用户
>>> $user = AppUser::first();
=> <app> {
id: "1",
name: "zhang jinglin",
email: "zjl@example.com",
created_at: "2015-03-31 03:24:55",
updated_at: "2015-03-31 03:24:55"
}
#获取用户文章
>>> $user->articles()->toArray();
BadMethodCallException with message 'Call to undefined method IlluminateDatabaseQueryBuilder::toArray()'
>>> $user->articles->toArray();
=> [
[
"id" => "1",
"user_id" => "1",
"title" => "User 1 Article",
"body" => "User 1 Body",
"published_at" => "2015-03-31 08:00:00",
"created_at" => "2015-03-31 04:17:58",
"updated_at" => "2015-03-31 04:17:58",
"excerpt" => null
]
]
#为什么使用 $user->articles 而不是 #user->articles()?
#事实上,$user->articles()返回的是关系,如果你想用 articles() 你需要这样用
>>> $user->articles()->get()->toArray();
=> [
[
"id" => "1",
"user_id" => "1",
"title" => "User 1 Article",
"body" => "User 1 Body",
"published_at" => "2015-03-31 08:00:00",
"created_at" => "2015-03-31 04:17:58",
"updated_at" => "2015-03-31 04:17:58",
"excerpt" => null
]
]
#你只能使用 articles() 来进行下一步的工作,比如下面的查询
$user->articles()->where('title', 'User 1 Article')->get();
#我们也可以通过 article 获取 user
>>> $article = AppArticle::first();
=> <app> {
id: "1",
user_id: "1",
title: "User 1 Article",
body: "User 1 Body",
published_at: "2015-03-31 08:00:00",
created_at: "2015-03-31 04:17:58",
updated_at: "2015-03-31 04:17:58",
excerpt: null
}
>>> $article->user;
=> <app> {
id: "1",
name: "zhang jinglin",
email: "zjl@example.com",
created_at: "2015-03-31 03:24:55",
updated_at: "2015-03-31 03:24:55"
}
>>>
</app></app></app>