如何从模型文件访问功能

时间:2020-11-05 11:26:02

标签: php laravel laravel-5 eloquent

我在项目中使用laravel 7.24和php 7.4的

im 我想要的是从根本上创建3表之间的关系,并在“一个”查询中使用它们。 具体来说,我需要从我的订单详细信息页面访问“订购的产品”。

public function orderdetail($id)
{   //certainorder model access to 'ShoppingCard'model from below
    $orderDetails  = CertainOrder::with('ShoppingCard.shoppingCardProducts.product')
    ->where('ShoppingCard.id' , $id)->firstorFail();
    return view('orderdetails', compact ('orderDetails'));
}

CertainOrder模型从顶部访问“ ShoppingCard”模型,在ShoppingCard模型中,它包含shoppingCardProducts函数(您将在下面看到)以及与shoppingCardProducts函数的“产品”表有关。问题是关系中的某些问题是错误的,我无法从shoppingcardproduct获取数据

class ShoppingCard extends Model
{
protected $table = "shopping_card";

protected $fillable = ['id', 'user_id', 'created_at','updated_at'];

public function shoppingCardProducts()
{
    return $this->hasMany('App\ShoppingCardProduct');
}
    class CertainOrder extends Model
    {
    protected $table = "certain_orders";
    protected $guarded = [];


    public function shoppingCard()
    {
        return $this->belongsTo(ShoppingCard::class, 'sepet_id');
        //sepet_id is a foreign key.
    }
class ShoppingCardProduct extends Model
 {
use SoftDeletes;

protected $table = "shopping_card_product";

protected $fillable = ['id', 'sepet_id', 'urun_id','quantity','price','status','created_at','updated_at','deleted_at'];


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

 

1 个答案:

答案 0 :(得分:1)

我认为您在代码中的某个地方错过了它

 class ShoppingCard extends Model
{
protected $table = "shopping_card";

protected $fillable = ['id', 'user_id', 'created_at','updated_at'];

public function shoppingCardProducts()
{
    return $this->hasMany('App\ShoppingCardProduct');
}

public function CertainOrder(){
    return $this->hasMany('path\to\model');
}

public function ShoppingCardProduct(){
    return $this->hasMany('path\to\model');
}
}

    class CertainOrder extends Model
    {
    protected $table = "certain_orders";
    protected $guarded = [];


    public function shoppingCard()
    {
        return $this->belongsTo('App\path\to\model', 'sepet_id');
        //sepet_id is a foreign key.
    }
}

class ShoppingCardProduct extends Model
 {
use SoftDeletes;

protected $table = "shopping_card_product";

protected $fillable = ['id', 'sepet_id', 'urun_id','quantity','price','status','created_at','updated_at','deleted_at'];


public function ShoppingCard()
{
    return $this->belongsTo('App\ShoppingCard');
}

}

以这种方式拨打电话

  public function orderdetail($id)
{   //certainorder model access to 'ShoppingCard'model from below
    $orderDetails  = ShoppingCard::with('CertainOrder, ShoppingCardProduct')
    ->where('id' , $id)->firstorFail();
    return view('orderdetails', compact ('orderDetails'));
}