首页 文章

如何将MySQL查询转换为Eloquent Relationships?

提问于
浏览
0

我真的不知道我会搜索什么词或术语 . 我还阅读了laravel 5.7,https://laravel.com/docs/5.7/eloquent-relationships#many-to-many-polymorphic-relations中的文档 .

但我仍然无法找到我想要的东西 .

The result that I am expecting is this in MySQL:

SELECT id as product_id, (SELECT name FROM products WHERE id = transactions.product_id), created_at FROM transactions WHERE user_id = 1

This is the result of the mysql query:

我已经有一个模特:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Transactions extends Model
{
    protected $table = 'transactions';
    protected $fillable = [
        'user_id', 'product_id'
    ];

    public function product()
    {
        return $this->hasOne('App\Products')->select('name');
    }
}
?>

然后在我的控制器中:

public function transactions()
{
    $transactions = new Transactions::where('user_id',Auth::id())->product;
    return view('transactions', ['transactions' => $transactions]);
}

1 回答

  • 1

    你应该使用 belongsTo() 关系 . 交易属于一个产品,产品有很多交易 .

    此外,您可以(或者更好)将模型重命名为单元格 . 然后你不需要使用 protected $table .

    它不一定只选择 name .

    交易模式:

    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    
    class Transaction extends Model
    {
        protected $fillable = ['user_id', 'product_id'];
    
        public function product()
        {
            return $this->belongsTo('App\Product');
        }
    }
    

    控制器:

    public function transactions()
    {
        $transactions = Transaction::with('product')
            ->where('user_id', Auth::id())
            ->get();
    
        return view('transactions', ['transactions' => $transactions]);
    }
    

    视图:

    @foreach($transactions as $transaction)
        echo $transaction->product_id; //attribute product_id of transaction
        echo $transaction->product->id; //attribute id of product
        echo $transaction->product->name;  //attribute name of product
    @endforeach
    

相关问题