Php laravel雄辩关系一对多返回空
当我获取进货数据(belongsTo)时,产品数据总是返回null 这是我的产品型号:Php laravel雄辩关系一对多返回空,php,mysql,laravel,relationship,laravel-eloquent,Php,Mysql,Laravel,Relationship,Laravel Eloquent,当我获取进货数据(belongsTo)时,产品数据总是返回null 这是我的产品型号: <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Product extends Model { use SoftDeletes; protected $guarded = [ 'id',
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Product extends Model
{
use SoftDeletes;
protected $guarded = [
'id', 'created_at', 'updated_at', 'deleted_at',
];
public function transaction_details()
{
return $this->hasMany('App\Transaction_detail');
}
public function incoming_goods()
{
return $this->hasMany('App\Incoming_good');
}
}
我尝试使用alies,但它仍然返回产品数据null。希望您能帮助我:)为了将急切加载的
产品
s与接收的产品
s匹配,Laravel需要选择外键。由于您没有在选择列表中包含外键(product\u id
),因此Laravel在检索相关记录后无法匹配它们。因此,您所有的产品
关系都将为空。将外键添加到选择列表中,您应该会很好
$data = Incoming_good::select('id', 'product_id', 'stock', 'note', 'created_at')
->with('product')
->get();
为了将急切加载的
产品
s与接收的货物
s匹配,Laravel需要选择外键。由于您没有在选择列表中包含外键(product\u id
),因此Laravel在检索相关记录后无法匹配它们。因此,您所有的产品
关系都将为空。将外键添加到选择列表中,您应该会很好
$data = Incoming_good::select('id', 'product_id', 'stock', 'note', 'created_at')
->with('product')
->get();
请自行添加查询代码。您必须指定相关模型中的哪些字段是主模型的外键。显示控制器代码您从何处获得产品!!这是因为表名。。。Laravel将名为Something1\u Something2的表视为Something1和Something2之间的透视表,尝试添加
$table->integer('product_id')->unsigned()$表->外部('product_id')->引用('id')->on('products')->onDelete('cascade')代码>然后刷新数据库并再次测试。请自行添加查询代码。您必须指定相关模型中的哪些字段是主模型的外键。显示控制器代码您从何处获得产品!!这是因为表名。。。Laravel将名为Something1\u Something2的表视为Something1和Something2之间的透视表,尝试添加$table->integer('product_id')->unsigned()$表->外部('product_id')->引用('id')->on('products')->onDelete('cascade')代码>然后刷新你的数据库并再次测试。哇,真是太棒了!我真的很尴尬知道解决办法很简单:“顺便说一句,谢谢你,这是工作!我真的很尴尬知道解决办法很简单:“顺便说一句,非常感谢
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTableIncomingGoods extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('incoming_goods', function (Blueprint $table) {
$table->increments('id');
$table->integer('product_id');
$table->integer('stock');
$table->text('note')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('incoming_goods');
}
}
$data = Incoming_good::select('id', 'stock', 'note', 'created_at')->with('product')->get();
$data = Incoming_good::select('id', 'product_id', 'stock', 'note', 'created_at')
->with('product')
->get();