chr*_*roy 0 laravel eloquent laravel-4
我很擅长使用Laravel,因此对Eloquent来说.我对Eloquent的桌子关系感到困惑.
现在我了解了如何实现简单连接,例如Laravel 4.2文档中的示例,该文档对于一对多关系,其中a comment属于一个post,但a post可以有很多comments.他们使用这种语法从一篇文章中获取评论:
Post::find(1)->comments;
Run Code Online (Sandbox Code Playgroud)
在MySQL中,它可能是:
SELECT * FROM comments
JOIN posts ON posts.id=comments.post_id
WHERE posts.id=1
Run Code Online (Sandbox Code Playgroud)
如果我想要得到的结果是这样的,不仅仅是一行:
SELECT * FROM comments
JOIN posts ON posts.id=comments.post_id
Run Code Online (Sandbox Code Playgroud)
根据我上面给出的例子,我知道它没有多大意义.但是我如何在Eloquent中做到这一点?
为了提供更多细节,我实际上要做的是显示我的两个表的连接结果,assets以及asset_classifications.一个asset属于一个asset_classification,并且asset_classification有许多assets.
我正在尝试显示assets包含其中的表格数据asset_classifications.在MySQL中,它是这样的:
SELECT * FROM assets
JOIN asset_classifications ON asset_classifications.id=assets.classification_id
Run Code Online (Sandbox Code Playgroud)
我怎样才能在Eloquent中执行它?
我猜你对SQL有点过于依赖了:)尝试在连接之外思考并在模型和melattionship中查询更多,因为Laravel会为你处理所有的抽象.
所以你有一个资产模型:
class Asset extends Eloquent
{
public function classification()
{
return $this->belongsTo('AssetClassification');
}
}
Run Code Online (Sandbox Code Playgroud)
......和AssetClassification门:
class AssetClassification extends Eloquent
{
public function assets()
{
return $this->hasMany('Asset');
}
}
Run Code Online (Sandbox Code Playgroud)
现在他们已经联系在一起,你可以随心所欲.如果要输出所有资产及其分类,没问题:
$assets = Asset::all();
foreach($assets as $asset)
{
echo "{$asset->name}" is classified as {$asset->classification}";
}
Run Code Online (Sandbox Code Playgroud)
或者反过来说:
$classifications = AssetClassification::all();
foreach($classifications as $classification)
{
echo "{$classification->name} has the following assets:";
foreach($classification->assets as $asset)
{ ... }
}
Run Code Online (Sandbox Code Playgroud)
作为一个数组,这看起来像
[0] => [
'id' => 1
'name' => 'asset_name_1',
],
[1] => [
'id' => 2
'name' => 'asset_name_2',
],
Run Code Online (Sandbox Code Playgroud)
你明白了.问题是,您对每次迭代执行单独的查询.这就是为什么你应该使用预先加载来不加载所有资产以及它们的依赖项:
$assets = Asset::with('classification')->get();
Run Code Online (Sandbox Code Playgroud)
现在你有一个像这样的数组:
[0] => [
'id' => 1
'name' => 'asset_name_1',
'classification' => AssetClassiciation-Object
],
[1] => [
'id' => 2
'name' => 'asset_name_2',
'classification' => AssetClassiciation-Object
],
Run Code Online (Sandbox Code Playgroud)
因此,现在您可以循环访问资产及其分类,而无需进行任何进一步的SQL查询.