【问题标题】:how to return all value in pivot table in Laravel 5.4如何在 Laravel 5.4 中返回数据透视表中的所有值
【发布时间】:2018-03-06 08:27:59
【问题描述】:

我得到了包含以下内容的数据透视表 帐户ID article_id created_at 更新时间

如何在 View 中检索所有这些。我有 2 个模型账号和文章

class Account extends Model
{
    public function articles()
    {
         return $this->belongsToMany('App\Article','accountsarticles')->withPivot('account_id','article_id')->withTimestamps();
    }
}

class Article extends Model
{
    public function accounts()
    {
        return $this->belongsToMany('App\Account','accountsarticles')->withPivot('account_id','article_id')->withTimestamps();
    }
}

我也有这样的控制器

class AccountsArticlesController extends Controller
{
    public function index()
    {
        /*If i use this 1 i can get all of column data*/
        $accountsarticles=DB::table('accountsarticles')->get();

        /*If i use this 1 i only get created_at and updated_at*/
        $acc = Account::all();
        return view('accountsarticles.index',['accountsarticles'=>$accountsarticles]);
    }
}

现在我不使用 MVC 就这样检索它

@foreach($accountsarticles as $article)
    <tr>
        <td>{{$article->created_at}}</td>
        <td>{{$article->updated_at}}</td>
        <td>{{$article->account_id}}</td>
        <td>{{$article->article_id}}</td>
    </tr>
@endforeach

我想知道如何检索该枢轴中的所有列,以便在视图返回时显示该列中的所有数据。

【问题讨论】:

    标签: php model laravel-5.4


    【解决方案1】:

    使用以下语法$model-&gt;pivot-&gt;field_name

    在你的情况下,它将是:

    //to fetch account id
    $article->pivot->account_id
    
    //to fetch article id
    $article->pivot->article_id
    

    【讨论】:

    • 我已经尝试过了,但它给了我“尝试获取非对象的属性”
    • 您没有在视图中发送模型集合。您正在使用 DB 仅从表名中获取数据 $accountsarticles=DB::table('accountsarticles')-&gt;get() 这就是它给出错误的原因。
    • @Student 将$acc = Account::all() 数据发送到视图。
    • 我已经改成$acc了,但是没有返回account_id和article_id。即使我已经使用了pivot->field_name。仅返回的 created_at 和 updated_at
    • 你想在视图中显示什么?特定帐户的文章 ? @学生
    猜你喜欢
    • 2017-09-19
    • 2017-12-15
    • 2018-02-26
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    • 1970-01-01
    • 2019-12-01
    • 1970-01-01
    相关资源
    最近更新 更多