【发布时间】:2018-12-13 22:17:38
【问题描述】:
我对 Laravel 非常陌生。你可以帮我解决一个小问题: 我不能在集合中返回,只能返回模型中定义的关系中特定列的值。我会解释:
我有 2 张桌子:
1 - 托莫斯
2 - 文档
迁移:
1- 托莫斯
private $table = 'tomos';
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create($this->table, function (Blueprint $table) {
$table->increments('id');
$table->string('name')->nullable(false);
$table->text('description')->nullable(true);
$table->boolean('active')->default(true);
$table->timestamps();
});
}
2- 文件
private $table = 'documents';
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create($this->table, function (Blueprint $table) {
$table->increments('id');
$table->date('date')->nullable(false);
$table->integer('provider_id');
$table->integer('tomo_id');
$table->string('folio')->nullable(false);
$table->integer('user_id');
$table->text('description');
$table->timestamps();
$table->foreign('provider_id')
->references('id')->on('providers');
$table->foreign('tomo_id')
->references('id')->on('tomos');
$table->foreign('user_id')
->references('id')->on('users');
});
}
关系
1- 托莫
public function document()
{
return $this->hasMany(Document::class);
}
2- 文档
public function tomo()
{
return $this->belongsTo(Tomo::class);
}
控制器
class Documents extends Controller
{
public function read(Request $request)
{
$provider = $request->only('id');
$documents = Document::select(['id', 'date', 'tomo_id', 'description'])
->with([
'tomo' => function ($query) {
$query->select('id', 'name');
}
])->orderBy('date', 'ASC')
->paginate(25);
return $documents;
}
}
我收到以下 JSON 响应:
current_page 1
data […]
0 {…}
id 2
date 2018-12-01
tomo_id 1
description 1
tomo {…}
id 1
name Tomo 1
但是......我不希望键('tomo')返回一个对象,我希望它以字符串的形式返回列('name')的值。示例:
current_page 1
data […]
0 {…}
id 2
date 2018-12-01
tomo_id 1
description 1
tomo Tomo 1
非常感谢您..
【问题讨论】:
-
最快的方法是使用join而不是relation,我会想办法解决这个问题。
-
哦,你可以使用自定义属性,我现在写一个答案
标签: laravel relationship