![](/img/trans.png)
[英]Laravel 5.7: How to recursively get an attribute from a nested Eloquent relationship?
[英]How to get data from Laravel nested relationship?
我是 Laravel 的新手。 我在 Laravel 中很难建立一个非常嵌套的关系才能正常工作。
想要的行为如下,
我有 5 个模型。 Purchase
、 Inventory
、 Slab
、 Scarting
和地FloorTile
。
我在采购模型和库存模型之间有一对一的关系,而库存与平板、划痕和地板有进一步的关系。
我有购买ID和希望从中获取数据inventory
表,然后得到一个slab_id
, scarting_id
或floorTile_id
从inventory
表,并从各自的表中获取数据。
与inventory id
slab_id
, slab_id
、 scarting_id
和floorTile_id
可以是多个。
我不知道如何在每次迭代中获取数据。
购买型号:
<?php
namespace App;
use App\Inventory;
use Illuminate\Database\Eloquent\Model;
class Purchase extends Model
{
public function inventory()
{
return $this->hasOne('App\Inventory');
}
}
库存模型:
<?php
namespace App;
use App\Slab;
use App\Scarting;
use App\FloorTile;
use App\Purchase;
Use App\StandardSize;
use Illuminate\Database\Eloquent\Model;
class Inventory extends Model
{
public function purchase()
{
return $this->belongsTo('App\Purchase');
}
public function standatdSize()
{
return $this->hasOne('App\StandardSize');
}
public function slab()
{
return $this->hasOne('App\Slab');
}
public function scarting()
{
return $this->hasOne('App\Scarting');
}
public function floorTile()
{
return $this->hasOne('App\FloorTile');
}
}
我试过这个:
$purchase = Purchase::where('factoryName', $factoryName)->with('inventory.slab')->get();
结果如下:
{
"id": 36,
"fname": "Sama",
"lname": "Jojo",
"factoryName": "Sama Inc.",
"cnic": "3216542",
"area": "Johar town",
"city": "Lahore",
"province": "Punjab",
"phone1": "45678912345",
"phone2": "45678912345",
"inventory_ID": 10,
"created_at": "2019-03-19 12:11:45",
"updated_at": "2019-03-19 12:11:45",
"inventory": {
"id": 10,
"purchase_id": 36,
"marbleType": "1",
"totalSquareFt": 25,
"priceperSquareFt": 230,
"totalPurchasePrice": 25000,
"standardSize_ID": "5",
"salePrice": 250,
"miliMeter": "6mm",
"slab_ID": 1,
"scarting_ID": null,
"floorTile_ID": null,
"created_at": "2019-03-19 12:11:45",
"updated_at": "2019-03-19 12:11:45",
"slab": null
}
}
即使有数据可用于平板,但仍显示为 NULL。
如果您的记录是slab_id
而不是slab_ID
这样Laravel会为您做这件事对您来说会更容易,但是您没有遵循Laravel 的命名约定,这很好,但您必须告诉Laravel 您正在使用自己的命名约定,它会很好地接受它。 我在下面提供了一个例子。
public function slab()
{
return $this->hasOne('App\Slab', 'id', 'slab_ID');
}
$this->hasOne('App\\Model', 'foreign_key', 'local_key');
外键是您尝试检索的模型的主键, local_key 是它在此模型中调用的引用,通常是model_id
,在这种情况下是slab_ID
。
在这种情况下, local_key = $this->id
和foreign_key = App\\Slab
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.