我有一个像这样的mySQL DB架构:
table RECIPES:
int id, PK;
int salesman_id;
int doctor_id;
date order_date;
int status;
table RECIPE_STATUS:
int id, PK;
int recipe_status_code;
varchar recipe_status_name;
在Laravel中我有以下php类:
AdminRecipesController.php
namespace RatCMS\Controllers;
use App\Http\Controllers\Controller;
use Auth;
use RatCMS\Models\Recipes;
use RatCMS\Models\RecipeStatus;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
class AdminRecipesController extends Controller
{
public function index()
{
$recipes = Recipes::with('recipeStatus')->get();
return view('admin.recipes.news', compact('recipes'));
}
}
Recipes.php
<?php
namespace RatCMS\Models;
use Illuminate\Database\Eloquent\Model;
class Recipes extends Model
{
protected $table = 'RECIPES';
protected $fillable = ['salesman_id', 'doctor_id', 'order_date', 'status'];
public function recipeStatus() {
return $this->hasOne(\RatCMS\Models\RecipeStatus::class, 'recipe_status_code', 'status');
}
}
RecipeStatus.php
<?php
namespace RatCMS\Models;
use Illuminate\Database\Eloquent\Model;
class RecipeStatus extends Model
{
protected $table = 'RECIPE_STATUS';
protected $fillable = [];
public function recipes() {
return $this->belongsTo(\RatCMS\Models\Recipes::class);
}
}
blade view
<div class="box-body">
@include('admin.partials.session_success')
@if($recipes->isEmpty())
<p class="text-center">No recipes available.</p>
@else
<table class="table table-bordered">
<tr>
<th style="width: 10px">#</th>
<th>Salesman</th>
<th>Doctor</th>
<th>Date</th>
<th>Status</th>
<th style="width:100px">Actions</th>
</tr>
@foreach($recipes as $recipe)
{{ $recipe }}
<tr>
<td>{{ $recipe->id }}</td>
<td>{{ $recipe->salesman_id }}</td>
<td>{{ $recipe->doctor_id }}</td>
<td>{{ $recipe->order_date }}</td>
<td>{{ $recipe->recipe_status->recipe_status_name }}</td>
<td>
<form style="display: inline-block" action="{{ url('admin/recipes/' . $recipe->id) }}" method="POST">
{{ csrf_field() }}
<input name="_method" type="hidden" value="DELETE">
<button type="submit" class="btn btn-danger"><i class="fa fa-close" aria-hidden="true"></i> Delete</button>
</form>
</td>
</tr>
@endforeach
</table>
@endif
</div>
当我在视图中执行{{ $recipe }}
时,我得到以下结果:
{ “ID”:1, “salesman_id”: “4”, “doctor_id”: “3”, “order_date的”:NULL, “状态”: “0”, “recipe_status”:{ “ID”:1 ,“recipe_status_code”:“0”,“recipe_status_name”:“未收到”}}
所以有一些数据由Eloquent返回有关配方状态(未接收的文本),但是当我{{ $recipe->recipe_status }}
时它每次都失败。甚至$ recipes ['recipe_status']都没有帮助。
有人可以帮忙吗?感谢
答案 0 :(得分:0)
关系应为belongsTo()
:
public function recipeStatus() {
return $this->belongsTo(\RatCMS\Models\RecipeStatus::class, 'status', 'recipe_status_code');
}
如果关系正确,您的代码会将关系数据添加到集合中,这样您就可以获得状态:
$recipe->recipeStatus->recipe_status_name