【发布时间】:2018-04-11 12:24:10
【问题描述】:
当我得到incoming_goods数据(belongsTo)时,产品数据总是返回null。
这是我的产品型号:
<?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');
}
}
这是我的 Incoming_good 模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Incoming_good extends Model
{
protected $guarded = [
'id', 'created_at', 'updated_at',
];
public function product()
{
return $this->belongsTo('App\Product');
}
}
这是我对这两个表的迁移:
产品表迁移:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 50);
$table->integer('price');
$table->integer('stock')->nullable();
$table->integer('available');
$table->string('image1', 190)->nullable();
$table->string('image2', 190)->nullable();
$table->string('image3', 190)->nullable();
$table->string('image4', 190)->nullable();
$table->string('image5', 190)->nullable();
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
incoming_goods 迁移:
<?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');
}
}
这是我显示 incomong_goods 数据和产品(关系 belongsTo)的代码:
$data = Incoming_good::select('id', 'stock', 'note', 'created_at')->with('product')->get();
我尝试使用别名,但它仍然返回产品数据 null。希望你能帮助我:)
【问题讨论】:
-
请自行添加查询代码
-
您必须指定相关模型中的哪些字段是主模型的外键。
-
显示控制器代码你从哪里得到的产品!!
-
这是因为表名... Laravel 将名为Something1_Something2 的表视为Something1 和Something2 之间的数据透视表
-
尝试添加
$table->integer('product_id')->unsigned(); $table->foreign('product_id') ->references('id')->on('products') ->onDelete('cascade');然后刷新你的数据库并再次测试。
标签: php mysql laravel relationship laravel-eloquent