2016-09-28 45 views
1

我有模式:如何将数据传递给Laravel中的相关表格?

class Product extends Model 
{ 
    public function translate() 
    { 
     return $this->hasMany("App\ProductTranslate", "objectId", "id")->where('language', self::$language); 
    } 
} 

当我将数据添加到表Product我应该将数据添加到相关表ProductTranslate

我试图这样做,因为:

$product = new Product(); 
$product->title = "Name"; 
$product->translate()->name = "Value" 

回答

0

你有hasMany关系,因此,当你拨打:

$product->translate()->get() 

$product->translate 

你会得到一个雄辩Collection类型App\ProductTranslate所以你像他们这样遍历它们:

$product = new Product(); 
$product->title = "Name"; 
foreach ($product->translate as $translation) { 
    $translation->name = "Value"; 
} 
+0

,以查看对于我必须使用'的foreach '如果桌子上有笔记? – Babaev

+0

正如我所说的......你使用'hasMany'关系,它总是返回一组模型。如果你在这里犯了一个错误 - 你可以尝试'belongsTo'关系。我不知道你的桌子结构。 –

+0

然后我应该使用:'$ product = new Product(); $产品 - 用( “翻译”)>?' – Babaev

0

存储对象在数组中,然后传递数组,以查看

$all_data = array() 
for($i=0; $i< count($product); $i++) 
{ 
    $product = new Product(); 
    $product->title = "Name"; 
    $product->translate()->name = "Value"; 

    $all_data[$i] = $product; 
} 

通行证数据从控制器

return view('admin.page')->with('all_data', $all_data) 

UI部分

<table id="table-data" class="table table-bordered table-striped"> 
    <thead> 
    <tr> 
     <th width="5%" class="text-center">No.</th> 
     <th>Name</th> 
    </tr> 
    </thead> 
    <tbody> 
    <?php $i = 1; ?> 
    @foreach($all_data as $data) 
     <tr> 
     <td width="5%"><?php echo $i; ?></td> 
     <td>{{ $data->name }}</td>  
     </tr> 
    <?php $i++; ?> 
    @endforeach  
    </tbody> 
</table> 
相关问题