简体   繁体   English

Laravel 4模型关系如何工作?

[英]How does it works the Laravel 4 model relationships?

I wish to know how works the laravel 4 relationships in the model. 我想知道模型中laravel 4关系的工作方式。 This question is because i'm trying to get the rows from 2 tables with relation and not success till now. 这个问题是因为我正在尝试从2个具有相关性的表中获取行,但到目前为止还没有成功。

class Products extends Eloquent {

protected $table = "Products";
protected $primaryKey = "ProductId";

public function plandetail()
{
        return $this->belongsTo("PlanDetail", "PlanDetail.ProductId")->select( array("ProductId", "Order") );
}

public function getProductsPlan($dealerId)
{
    return $this->with( "plandetail" )->where("Products.DealerId", $dealerId)->get();
}
} // end model

// In my controller

$product = new Products();
$products = $product->getProductsPlan($id);

foreach( $products as $product )
{
     print_r($product); // prints only the rows from the Products table
                        // not the PlanDetail table.
}

In the output is just print the product records and not the PlanDetail table rows. 在输出中仅打印产品记录,而不打印PlanDetail表行。 Do i need to add a join with the PlanDetail table to get these rows? 我是否需要添加与PlanDetail表的联接才能获取这些行?

This is one example row of what im getting now: 这是即时消息的示例行:

Products Object ( [table:protected] => Products [primaryKey:protected] => ProductId [errors:Products:private] => [rules:Products:private] => Array ( [ProductBaseId] => required|numeric [DealerId] => required|numeric [ProductName] => required|max:255 [DisplayName] => required|max:255 [Bullets] => required [Cost] => required|numeric [SellingPrice] => required|numeric [UseWebServicePricing] => required|boolean [Term] => required|numeric [Type] => required|numeric [Deductible] => required|numeric [VehiclePlan] => required|numeric [Mileage] => required|numeric [TireRotation] => required|numeric [Interval] => required|numeric [UseRangePricing] => required|boolean [IsTaxable] => required|boolean [NotRegulated] => required|boolean [CreatedOn] => required [CreatedBy] => required [ModifiedBy] => required [ModifiedOn] => required ) [connection:protected] => [perPage:protected] => 15 [incrementing] => 1 [timestamps] => 1 [attributes:protected] => Array ( [ProductId] => 3 [ProductBaseId] => 84 [DealerId] => 50 [ProductName] => Vehicle Service Contract [DisplayName] => US Warranty Service Contract [ProductDescription] => [Bullets] => Warranty Proteccion for the covered components,Rental Car Coverage,Towling Coverage,, [Cost] => 0.0 [SellingPrice] => 0.0 [BrochureImage] => [PDFContrator] => [UseWebServicePricing] => 1 [UseManualPricing] => 0 [BrochureHeight] => 0 [BrochureWidth] => 0 [Term] => 36 [Type] => Platinum [Deductible] => 100 [VehiclePlan] => None [Mileage] => 36000 [TireRotation] => 0 [Interval] => 0 [PENProductId] => 0 [DMSProductId] => 16 [CreatedBy] => GREIVIN BRITTON [CreatedOn] => 2015-01-08 22:26:47.000 [UseRangePricing] => 0 [ModifiedBy] => GREIVIN BRITTON [ModifiedOn] => 2015-01-28 15:06:11.000 [IsTaxable] => 0 [NotRegulated] => 0 ) [original:protected] => Array ( [ProductId] => 3 [ProductBaseId] => 84 [DealerId] => 50 [ProductName] => Vehicle Service Contract [DisplayName] => US Warranty Service Contract [ProductDescription] => [Bullets] => Warranty Proteccion for the covered components,Rental Car Coverage,Towling Coverage,, [Cost] => 0.0 [SellingPrice] => 0.0 [BrochureImage] => [PDFContrator] => [UseWebServicePricing] => 1 [UseManualPricing] => 0 [BrochureHeight] => 0 [BrochureWidth] => 0 [Term] => 36 [Type] => Platinum [Deductible] => 100 [VehiclePlan] => None [Mileage] => 36000 [TireRotation] => 0 [Interval] => 0 [PENProductId] => 0 [DMSProductId] => 16 [CreatedBy] => GREIVIN BRITTON [CreatedOn] => 2015-01-08 22:26:47.000 [UseRangePricing] => 0 [ModifiedBy] => GREIVIN BRITTON [ModifiedOn] => 2015-01-28 15:06:11.000 [IsTaxable] => 0 [NotRegulated] => 0 ) [relations:protected] => Array ( [plandetail] => ) [hidden:protected] => Array ( ) [visible:protected] => Array ( ) [appends:protected] => Array ( ) [fillable:protected] => Array ( ) [guarded:protected] => Array ( [0] => * ) [dates:protected] => Array ( ) [touches:protected] => Array ( ) [observables:protected] => Array ( ) [with:protected] => Array ( ) [morphClass:protected] => [exists] => 1 [softDelete:protected] => ) 

Thanks in advance :) 提前致谢 :)

It looks like there's a few things wrong here. 看来这里有些错误。

The belongsTo method expects the name of the relating model, and then the foreign key of that model on the Products table. belongsTo方法需要相关模型的名称,然后是Products表上该模型的外键。 It looks like your foreign key is actually on the relating model making this relationship either a hasOne or hasMany . 看起来您的外键实际上在相关模型上,使得此关系为hasOnehasMany In this case, since you say you are expecting 2 rows, I'm assuming hasMany . 在这种情况下,由于您说您期望2行,所以我假设hasMany

Additionally, the second argument of this only expects the name of the column. 此外,此参数的第二个参数仅需要列的名称。 It can already guess the name of the table because you gave it the relating model name. 它已经可以猜测表的名称,因为您为其指定了相关的模型名称。

With that in mind, this should be the relationship method you need. 考虑到这一点,这应该是您需要的关系方法。

public function plandetails()
{
    return $this->hasMany("PlanDetail", "ProductId")->select( array("ProductId", "Order") );
}

And the other function should be modified a bit. 并且其他功能应进行一些修改。 When you use with and you need to query based on the relation, you should pass in an array where the key is the name of the relation and the value is a callback function which will allow you to modify the query which will grab the relating items. 当您with使用并且需要根据该关系进行查询时,您应该传递一个数组,其中键是关系的名称,而值是一个回调函数,该函数将允许您修改查询以获取相关项。

public function getProductsPlan($dealerId)
{
    return $this->with(array("plandetail", function($q) use ($dealerId)
    {
        $q->where('DealerID', $dealerId);
    }))->get();
}

Now when you do this... 现在,当您这样做时...

$product = new Products();
$products = $product->getProductsPlan($id);

This should work... 这应该工作...

foreach( $products as $product ) {
    foreach($product->plandetails as $plandetail) {
        print_r($plandetail);
    }
}

I also modified the relating function name so you would have to update your getProductsPlan function to reflect that when you use with . 我还修改了相关的函数名称,因此在with使用时,您必须更新getProductsPlan函数以反映该函数。 When you use hasMany , it makes more sense and is easier to read when you make the function name plural. 当使用hasMany ,将函数名称设为复数会更有意义并且更易于阅读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM