繁体   English   中英

laravel父母关系属于

[英]laravel parent relationship belongsTo

我在输出关系数据时遇到问题,我试图从表示为producttypes的类中获取标题。尝试获取非对象的属性,我尝试了各种方法,但未获得期望的结果

class Product extends \Eloquent {

    public function producttype() {
        return $this->belongsTo('ProductTypes', 'producttype_id');
    }

}

class ProductTypes extends \Eloquent {

    public function products() {
        return $this->hasMany("Product", 'id');
    }
}

$product->producttype->title

更新资料

class ProductTypes extends \Eloquent {
    protected $fillable = ['keywords', 'description', 'title', 'slug'];
    protected $table = "producttypes";

    public function products() {
        return $this->hasMany("Product", 'product_id', 'id');
    }
}

class ProductVariations extends \Eloquent {
    protected $table = "productvariations";
    protected $fillable = ['product_id', 'producttype_id', 'price', 'quantity', 'discount', 'image'];


    public function product() {
        return $this->belongsTo('Product');
    }
}

public function show($id)
{
    $product = Product::with('producttype')->findOrFail($id)->get();

    return View::make('products.show')->withProduct($product);
}

显示页面

$product->producttype->title

您必须以这种方式获取数据库值

$product = Product::with('producttype')->get()

试试这个。

请将此代码放在其他所有内容的底部的route.php文件中。.仅供测试。

Route::get('/', function(){
     $product = Product::with('producttype')->get();
     dd($product);
});

get()方法将在具有多个对象的数组中返回结果,而firstOrfail将仅返回对象。 这就是为什么您会得到非对象方法调用异常的原因。 尝试dd()结果集,您将知道

您应该确保查询返回一个对象而不是一个集合。 如果使用的是where查询,除非您在查询中添加-> firstorfail(),否则您将获得对象的集合。 如果您使用的是'Model :: Find(id)',则可以获取对象,因此可以使用该方法。 看一下该部分末尾的红色的查询关系

你应该试试

public function show($id)
{
    $product = Product::Find($id);

     return View::make('products.show',['product'=>$product]); 
}

然后在您看来产品方法将可访问

 $product->producttype;
 $product->productvariation //You should add this method to the product class

暂无
暂无

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

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