public function posts ()
{return $this->hasMany (Post::class)->select (["id","user_id","title"]);
}
function query_end ()
{$queries = DB::getQueryLog ();
foreach ($queries as $i=>$query)
{Log::debug ("Query $i:" . JSON_encode ($query));
}
}
Artisan::command ('linson:query_one',function (){query_start ();
// Run your queries
$res = \App\User::with ('profile')->first (["id"]);
print_r ($res->toArray ());
// Then to retrieve everything since you enabled the logging:
query_end ();});
Artisan::command ('linson:query_many',function (){query_start ();
// Run your queries
$res = \App\User::with (['posts'=>function ($query){$query->orderBy ("id","asc");
}])->first (["id"]);
print_r ($res->toArray ());
// Then to retrieve everything since you enabled the logging:
query_end ();});
User::first ()->posts ()->where ("id",">=", 10)->get ();
User::with ("posts","profile")->first ();
1). 在 Posts.php 添加代码
public function user ()
{return $this->belongsTo (User::class)->select (["id","email"]);
}
2). 测试代码
λ pa tinker
Psy Shell v0.8.17 (PHP 7.0.10 鈥?cli) by Justin Hileman
>>> App\Post::with ("user")->first ();
=> App\Post {#747
id: 1,
user_id: 1,
title: "Ducimus asperiores fugiat reprehenderit et officia quos qui.",
created_at: "2018-03-11 02:38:54",
updated_at: "2018-03-11 02:38:54",
user: App\User {#751
id: 1,
email: "mayer.monte@example.com",
},
}
>>>