我真的不知道我会搜索什么词或术语 . 我还阅读了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 回答
你应该使用
belongsTo()
关系 . 交易属于一个产品,产品有很多交易 .此外,您可以(或者更好)将模型重命名为单元格 . 然后你不需要使用
protected $table
.它不一定只选择
name
.交易模式:
控制器:
视图: