如何将MySQL查询转换为雄辩的关系?

时间:2018-12-10 06:15:57

标签: relationship laravel-5.7

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

但是我仍然找不到我想要的东西。

我期望的结果是MySQL中的结果:

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

这是mysql查询的结果:
enter image description here

我已经有一个模型:

<?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 个答案:

答案 0 :(得分:0)

您应该使用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