【问题标题】:Return result from eloquent's saveMany in addition to parent data除了父数据之外,还从 eloquent 的 saveMany 中返回结果
【发布时间】:2017-03-18 19:56:01
【问题描述】:

使用Eloquent 的方法saveMany 将数据保存到数据库后,我想在一个JSON 块中同时返回parent datachild data。问题是在我当前的实现中,我可以返回一个或另一个,但不能同时返回。什么是最合适和最干净的方法?

我有 2 个模型:

  • Theader(即标头)
  • Line

关系是一对多的:

final class Theader extends Model 
{
    public $timestamps = false;
    protected $fillable = array('total_amount', 'name', 'description');

    public function lines()
    {
        return $this->hasMany('App\Line', 'header_id');
    }
}

final class Line extends Model 
{
    public $timestamps = false;
    protected $fillable = array('amount', 'description');

    public function theader()
    {
        return $this->belongsTo('App\Theader', 'header_id');
    }
}

当我插入新数据时::

  • 1 行转到theaders 表。生成唯一的id
  • 2 到 100 行将转到 lines 表。所有人都有相同的header_id

这是我想出的可行解决方案:

namespace App\Http\Controllers;

use App\Theader;
use App\Line;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class TheaderController extends Controller
{   
    public function create(Request $request){
        $input = $request->all();
        $input['name'] = 'My name';
        $input['description'] = 'My description';
        $input['lines'][] = [ 'name' => 'Test 1', 'amount' => 19 ];
        $input['lines'][] = [ 'name' => 'Test 2', 'amount' => 15 ];

        // first create Header
        $header = Theader::create($input);

        // now let's create lines
        $lines = [new Line($input['lines'][0]), new Line($input['lines'][1])];
        $header->lines()->saveMany($lines);

        return response()->json($header);
    }
}

在这个例子中 - 我如何一次返回标题 + 所有新插入的行?

我可以使用return response()->json($header);return response()->json($header)->lines;,但这些选项都不会同时返回headerlines

【问题讨论】:

    标签: php laravel-5 eloquent lumen


    【解决方案1】:

    您只需要在保存数据后重新加载lines 关系即可。

    这应该适合你:

    // save your lines to your header
    $header->lines()->saveMany($lines);
    
    // load/reload the related lines on the $header object
    $header->load('lines');
    
    return response()->json($header);
    

    【讨论】:

      【解决方案2】:

      你可以像这样返回两行

      return response()->json(compact('headers', 'lines')); 
      

      将所有内容都放在一个对象中

      $headers->lines = $lines;
      $headers->moreStuff = $moreStuff;
      return response()->json($headers); 
      

      【讨论】:

      • 这个变通方法确实有效!但在这种情况下,行不是“标题”数组的一部分,而是一个单独的实体。另一个问题是可能插入了其他列,例如“created_at”或具有默认值的列。我想查看所有新插入的数据。所以也许对行进行另一个查询会更容易..
      • 你是对的。检查我的更新,看看它是否对你有帮助。
      猜你喜欢
      • 2015-12-28
      • 2022-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多